-2

I'm an absolute beginner to coding in C and I'm attempting to practice by writing a program where a user responds to Yes/No questions in a series, like if it were a game.

The problem that I'm having is that after the first question is answered, and the second pops up, the program doesn't give me (the user) a chance to respond to it; the program abruptly ends.

Obviously, there must be something simple that I'm missing here to go from one question to another without it terminating. I'd appreciate any advice.

Here's what I've made so far:

#include <stdio.h>

char answer, answertwo;

int main()
{
    printf ("Are you laughing? (Y/N)\n" );
    scanf ("%c", &answer);

    if (answer == 'y' || answer == 'Y')
        printf("\nGood\n");
    else if (answer == 'n' || answer == 'N')
        printf("\nBye\n");

    printf("Do you want to read? (Y/N)\n ");
    scanf ("%c, &answertwo");
    if (answertwo == 'y' || answertwo == 'Y')
        printf("\nGood\n");
    else if (answertwo == 'n' || answertwo == 'N')
        printf("\nBye\n");

    return 0;
}
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • 1
    How did it go compiling `scanf ("%c, &answertwo");`? – Paul Rooney Feb 02 '17 at 22:18
  • The program asked the question, but then immediately ended after I responded, without printing what I specified it to do. – NightTower Feb 02 '17 at 22:20
  • Don't know whether to close as typo or dup: [The program doesn't stop on scanf(“%c”, &ch) line, why?](http://stackoverflow.com/questions/20306659/the-program-doesnt-stop-on-scanfc-ch-line-why) – 001 Feb 02 '17 at 22:20
  • I'm not someone else asking a question twice. >.> – NightTower Feb 02 '17 at 22:23
  • Why won't it compile? – NightTower Feb 02 '17 at 22:23
  • "I'm not someone else asking a question twice". Huh? Do you mean the duplicate? That's not saying you asked a question twice. It is saying someone else has asked the same question so go read that answer. – kaylum Feb 02 '17 at 22:26
  • lol You guys close typos? Isn't that kinda what this place is all about? Figuring out where people went wrong? – NightTower Feb 02 '17 at 22:34
  • Ah, I see how it would apply. The duplicate response is appropriate then. My bad. – NightTower Feb 02 '17 at 22:40
  • @PaulRooney the line you mention is undefined behaviour with no diagnostic required, typically compilers will compile it (modern compilers may issue a warning) – M.M Feb 02 '17 at 23:11

1 Answers1

0

Two things:

  1. You have a typo on the line scanf ("%c, &answertwo");, move the quote to the end of the first argument:

    scanf ("%c", &answertwo);
    
  2. The second call to scanf ends prematurely because it consumes the newline in stdin from the first call. Try replacing your format specifiers in scanf from "%c" to " %c" so that they will ignore whitespace before the actual character is input.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85