Reputation: 3953
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
Upvotes: 0
Views: 258
Reputation: 188
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);
Upvotes: 2
Reputation:
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.
}
Upvotes: 5