#define MAX_COMMAND_LEN 32
char command[MAX_COMMAND_LEN];
while (1) {
if (fgets(command, MAX_COMMAND_LEN, stdin) == NULL) {
perror("Error: standard function fgets has failed\n");
break;
}
if (command[strlen(command) -1] != '\n') {
printf("Error: command length must be less than or equal to 30 characters\n");
continue;
}
else {
printf("Error: command not found\n");
}
}
quit();
I have couple of problems which I’m not able to handle:
- When I press Enter, it stops the loop and doesn’t print the
command not foundmessage. - When I enter a command with a size bigger than 30 characters it prints both the
command not foundand thecommand length must be less than or equal to 30 charactersmessages. - When I enter a 64 size command it prints twice the 30-length message.
I believe it divides the input to 30-length segments and input each one of them, how do I overcome it? I tried to flush stdin, it does not work. I want to get rid of the rest of the input. How do I overcome all these problems?
For your second problem, it’s because
fgetsfetches the 31 (MAX_COMMAND_LEN, minus space for the terminating'\0'character) first characters, you notice it’s no newline and the next time around the loopfgetsfetches the remaining characters.