I have the following code in C:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *buf;
buf = malloc(sizeof(char) * 512);
while(strcmp(buf, "Exit!") != 0 )
{
printf("Enter something:");
fgets(buf, sizeof(char) * 512, stdin);
printf("You entered %s\n", buf);
printf("%d\n", strcmp(buf, "Exit!"));
}
}
The behavior I want is for the while
loop to terminate when the user enters the specified string
. From what I understand, I am able to use a char
pointer to represent a string
in C. I am storing the user input using fgets()
and comparing using the strcmp()
function. I added a debug statement that prints out the result of this comparison and it returns a positive integer when I enter "Exit!" which should terminate the while loop.
Could someone explain what I am missing? I believe it has something to do with a new line character or the C-String terminator \0
. How do I get the while loop to terminate when the user enters "Exit"?