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

7
  • 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?) Commented Jun 22, 2013 at 20:19
  • 1
    possible duplicate of Simple C scanf does not work? Commented Jun 22, 2013 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 Commented Jun 22, 2013 at 20:23
  • after scanf use flushall(); refer [link]phanderson.com/C/scanf.html Commented Jun 22, 2013 at 20:27
  • @JamesOkpeGeorge Titles are wrong (as so many times on SO). That question is a dupe. Commented Jun 22, 2013 at 20:27

2 Answers 2

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.
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked, but how do I eliminate the trailing line from scanf, i mean if there is a way to eliminate it
@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.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.