0

I recently started working with C programming language, about two or three days ago, but I encountered some problem when working with the do-while loop, This is part of my program that would not run.

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

int main(void){        
    char another_game   =   'Y';
    scanf("%c", &another_game);
    do{
        printf("\nWould you like to continue(Y/N)?");
        scanf("%c", &another_game);
    }while(toupper(another_game) == 'Y');
    return 0;
}

The loop is suppose to continue running as long as the user types 'Y' or 'y' when prompt to do so, but I noticed that after the program executes the loop the first time it just displays the question again and then the loop breaks. I tried using integers, for the user to type 1 when he wishes to continue or 0 when he wishes to quit, it worked, so I do not understand why this one would not. I would appreciate all help on solving this issue, thanks

George
  • 3,757
  • 9
  • 51
  • 86
  • 1
    `scanf("%c",...)` doesn't consume the newline. Your confirmation gets that newline. Use `scanf(" %c", &another_game);` to skip initial whitespace. (it's a duplicate many times, but I'm too lazy to search. Any takers?) – Daniel Fischer Jun 22 '13 at 20:19
  • 1
    possible duplicate of [Simple C scanf does not work?](http://stackoverflow.com/questions/3744776/simple-c-scanf-does-not-work) – rob mayoff Jun 22 '13 at 20:19
  • @robmayoff, sorry please, I am not asking why scanf does not work, I am asking why my program does not work. Thank you – George Jun 22 '13 at 20:23
  • after scanf use flushall(); refer [link]http://www.phanderson.com/C/scanf.html – Swapnil Jun 22 '13 at 20:27
  • @JamesOkpeGeorge Titles are wrong (as so many times on SO). That question **is** a dupe. –  Jun 22 '13 at 20:27
  • James, your program does not work because you are using `scanf` incorrectly. You do not understand what `scanf` is doing. – rob mayoff Jun 22 '13 at 20:28
  • @robmayoff, thanks I now understand why it did not work – George Jun 22 '13 at 20:39

2 Answers2

5

Because when you press <enter>, there's the trailing newline character in the stdin buffer. Better use fgets() instead:

char buf[0x10];
fgets(buf, sizeof(buf), stdin);
if (toupper(buf[0]) == 'Y') {
    // etc.
}
  • Thanks it worked, but how do I eliminate the trailing line from scanf, i mean if there is a way to eliminate it – George Jun 22 '13 at 20:37
  • @JamesOkpeGeorge I think Daniel Fischer's comment sums it up, but you should **really avoid using `scanf()`.** Its usage is less than unintuitive, and it's very easy to get it wrong, especially for a beginner. I don't use it either. I fear it. –  Jun 22 '13 at 20:39
2

I would use getchar as it would be more deterministic for your purposes. Also be sure to add one more getchar to check for newline character.

do { printf("enter Y/N\n"); } while( ( (toupper(getchar()) == 'Y') + (getchar() == '\n') ) == 2);

Bob Blogge
  • 186
  • 9