Good afternoon everybody, I am working with tokenizing input in C for a dummy shell program and I am having problems with an infinite loop. In my example code, workwithtokenstuff()
is executing infinitely. I have formed similar loops before, I am not sure why the scanf at the bottom is being skipped. Example input is "cd /dummydir". I have another strtok()
call to split the dir into another char array.
char inStr[255];
char *token;
scanf("%[^\n\r]", inStr);
token = strtok(inStr, " ");
while (strcmp(token, "exitcom") != 0) {
workwithtokenstuff();
scanf("%[^\n\r]", inStr);
token = strtok(inStr, " ");
}
The second scanf
is not really skipped, it's catching the newline character left on the input buffer by the previous scanf
, a space before the specifier is a usual fix, it consumes whitespace characters present in the buffer.
char inStr[255];
char *token;
scanf("%254[^\n\r]", inStr); // note the width limit, avoids buffer overflow
token = strtok(inStr, " ");
while (strcmp(token, "exitcom") != 0)
{
workwithtokenstuff(); // assuming this does not consume any more tokens
scanf(" %254[^\n\r]", inStr);
// ^ space here
token = strtok(inStr, " ");
}
For a more robust code, checking the return value of scanf
is advised.
Maybe you are aware of this, but nonetheless I'll mention that strtok
, among other things, changes the original string. If you need more details check How does the strtok function in C work?.