Search code examples
cfgets

Stop C program on matching user input


I am trying to break out of a loop when the user inputs the word "exit". If the user inputs anything aside from the word exit, I would like the program to skip a line and write a single "$". It works but is acting a little funny. Here's the code and the output:

int main()
{
    char input[5];
    int x = 5;
    while(x){
        printf("\n$");
        fgets(input, sizeof input, stdin);
        x = strcmp(input, "exit");
    }
}

Heres the output (on my input of: "a" return "asdfasdfasdf" return "exit" return):

$a

$asdfasdfasdf

$
$
$
$exit

Process returned 0 (0X0) execution time : 110.855s
Press ENTER to continue.

So my question is: Why are there so many extra "$"s? How do I only get one "$" per return?


Solution

  • Because you're only reading 4 characters per loop.