I'm having trouble wrapping my mind around parsing user input in c. My task (homework) is to read user input, then parse in the same way BASH does, so delimiters are ' ', |, >, etc. My (wrong) solution so far uses strtok. I've been advised to use sscanf, but haven't been able to wrap my mind around how that will work for all cases of user input.
I'd love a strategy that will point me in the right direction. Here's what I have so far:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define MAX_LINE 80
int main ()
{
const char delim[]=" \\|\\>\\1>\\2>\\>>\\2>>\\&>\\<";
char* args[MAX_LINE/2 + 1];
char tok[MAX_LINE];
char* token;
printf("osh>");
fgets(tok, sizeof(tok), stdin);
token = strtok(tok,delim);
while (token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, delim);
}
return 0;
}
"\\|\\>\\1>\\2>\\>>\\2>>\\&>\\<"supposed to be ? The C string equivalent of\|\>\1.\2>\>>\2>>\&>\<? You can't usestrtokto split on multi-char delimiters. It looks like you're trying to encompass a limited DFA in a singlestrtokcall, but that can only be done if the delimiters are all single-chars.