Reputation: 3315
I have the following simple C code where the user is expected to ask several questions in this particular order, among them are "What is your name?" and "What is your favourite color?". To make sure the answer the program gives matches the appropriate question, I do strcmp. However, when I input the correct question, it outputs two lines of ??? and terminates the program, skipping the second input rather than answering with "Bob" When I enter the incorrect input for the first question, it doesn't skip the second input.
What is wrong here and how can I fix it?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char questionOne[50];
char questionTwo[50];
scanf("%s", questionOne);
if(strcmp(questionOne, "What is your name?\n") == 0) {
printf("Bob\n");
}
else {
printf("???\n");
}
scanf("%s", questionTwo);
if(strcmp(questionTwo, "What is your favourite colour?\n") == 0) {
printf("Blue\n");
}
else {
printf("???\n");
}
return 0;
}
Upvotes: 0
Views: 311
Reputation: 371
"Scanf matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null character ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first." taken from Rafal Rawiki.
In other words, you don't get the whole sentence.
You can use fgets() to get the whole line
Upvotes: 1