0

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;
   }
Kurt Wagner
  • 3,295
  • 13
  • 44
  • 71
  • 1
    See this question: http://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf – Diego Basch Oct 08 '14 at 00:22
  • result of `sctcmp` == 0 if the strings are equal, negative if the the 1st string "literally less" than the second, and positive otherwise. – user3159253 Oct 08 '14 at 00:31
  • 1
    You will need to use `fgets()` to read lines of input, complete with trailing newline, which you can then compare with your strings (which already include a newline). `scanf("%s", questionOne);` skips blanks, tabs and newlines (collectively white space), reads one or more non-white-space characters, and stops scanning at the first white space. – Jonathan Leffler Oct 08 '14 at 00:35

1 Answers1

1

"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

Alex
  • 371
  • 1
  • 8