as a part of a homework assignment, I'm trying to read a single char from stdin, and act according to it:
char choice;
while (1) {
printf("please enter [y]es, [n]o or [m]aybe: ");
scanf("%c", choice);
fflush(stdin);
// validate input
if (choice == 'y' || choice == 'n' || choice == 'm') {
break;
} else {
printf("Please enter only \'y\', \'n\' or \'m\'!\n");
}
}
// do something with the input
if (choice == 'y') {
printf("you selected yes!\n");
}
for some reason, scanf captures both the char and the line-feed after, thus it proceeds to do something with the input and then also prints the "Please enter only 'y', 'n' or 'm'!" line. If I enter several characters on the stdin, it will print that line for all of them, while also performing correctly for the first char. So, for example:
$ ./run
please enter [y]es, [n]o or [m]aybe: y<return>
you selected yes!
Please enter only 'y', 'n' or 'm'!
$ ./run
please enter [y]es, [n]o or [m]aybe: yes<return>
you selected yes!
Please enter only 'y', 'n' or 'm'!
Please enter only 'y', 'n' or 'm'!
Please enter only 'y', 'n' or 'm'!
$
Same thing happens if I use getchar. What am I missing? thanks.
getchar is a function in C programming language that reads a single character from the standard input stream stdin, regardless of what it is, and returns it to the program. It is specified in ANSI-C and is the most basic input function in C. It is included in the stdio. h header file.
What is the problem with getchar()? Getchar() is one of the function which is used to take input from the user. But at a time it can take only one character.. if the user give more than one character also,it reads only one character.
Read a single character using the scanf() function Let's consider a program to read a character using the scanf() library function in C. As we can see, when we execute the above program, it takes a single character or group of characters using the scanf() library function instead of the getchar() function.
getchar() is a standard C function and is a safe function. you may come across non-standard function getch() or getche() if you are learning from multiple sources. Don't use them in your code.
You need a space between scanf("
and the %c
for it to work correctly:
scanf(" %c", &choice);
And you also need to use &choice, not choice!
EDIT: While you're at it, you might want to look into do while()
for that loop (unless the professor specifically said to use a break
) - do while
works great when validating user input!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With