The do...while
construct executes its body before the loop condition is checked. So by the time the loop "realizes" that the user entered done
, it has already tried to execute that input as a command inside the loop body.
The clearest way to fix this is to use break
:
while (1)
{
fgets(command, 50, stdin);
if (!strcmp(command, isDone)) break;
system(command);
}
The reason to structure it this way is that each iteration consists of both actions that should be done before the condition (reading in the user input) and actions that should be done after the condition (executing the command with system()
). Because of this, neither a do...while
or simple while
will allow you to structure your code intuitively. The break
keyword gives you a way to put the loop's termination condition in the middle of the loop body.