I am asking the user for input on whether they would like to quit the program or not. There are two snippets. One reads input using the scanf() function, while the second reads input using the fgets() function. Using scanf(), the program goes in an infinite loop. Using fgets(), the program performs as intended. Why does scanf() fail, and fgets() work? How can i correct it so that scanf() will work? Here is the code:
First is with scanf()
#include <stdio.h>
#include <string.h>
int main(void)
{
char yesNo[6];
printf("Enter [quit] to exit the program, or any key to continue");
scanf("%s", &yesNo[6]);
while (strcmp(yesNo,"quit
") != 0)
{
printf("Enter [quit] to exit the program, or any to continue");
scanf("%s", &yesNo[6]);
}
return 0;
}
Second is with fgets()
#include <stdio.h>
#include <string.h>
int main(void)
{
char yesNo[6];
printf("Enter[quit] to exit the program, or any key to continue: ");
fgets(yesNo, 6, stdin);
while (strcmp(yesNo,"quit
") != 0)
{
printf("Enter [quit] to exit the program, or any key to continue:");
fgets(yesNo, 6, stdin);
}
return 0;
}
See Question&Answers more detail:os