Reputation: 77
I try to write a program in C using the loop that repeated until a specific character is inputted from the keyboard. Here's my code:
#include <stdio.h>
main ()
{
char option;
do
{
printf("Enter q to quit: ");
option = getchar ();
}
while (option != 'q');
}
I've also tried with the scanf () but the result always the same. Here the output after I tried to test the program:
Enter q to quit: 3
Enter q to quit: Enter q to quit: 2
Enter q to quit: Enter q to quit: 1
Enter q to quit: Enter q to quit: q
Can anyone explain to me why the "Enter q to quit : " always appear twice and how can I fix it?
Upvotes: 1
Views: 8569
Reputation: 1081
When you enter q, you press q followed by enter (a new line character as far as C is concerned which is \n).
So when your loop returns to the beginning, '\n' is still in your input buffer and getch() automatically reads this and checks whether that equals q before returning to the beginning of your loop again (hence your text looks like it's printed twice).
Try using fgets like this:
fgets (option , 4 , stdin)
You have to make sure you have a character array big enough to hold this though so you should define
char option [3];
to hold 'q', the newline character '\n' and the termination character '\0';
fgets is quite a nice solution because it will only store up the the second argument worth of characters and throw away the rest. This means 1) you don't overflow your variables/arrays and 2) you don't have junk left in the input buffer :)
Upvotes: 3
Reputation: 90
getchar() function first reads from the buffer.If buffer is empty then and then it will read from standard input(i.e.screen).
Upvotes: 0
Reputation: 71
"Enter q to quit: " appears twice because your input buffer still has the new line character in it when it runs a second time.
Fix:
#include <stdio.h>
int main ()
{
char option;
do
{
printf("Enter q to quit: ");
option = getchar ();
while(getchar() != '\n'); //Enter this line here.
}
while (option != 'q');
}
Upvotes: 4
Reputation: 215330
You get it printed twice because when you hit enter, a line feed character \n
is appended to stdin.
You can discard that line feed character by adding an extra getchar:
do
{
printf("Enter q to quit: ");
option = getchar();
getchar(); // discard line feed
}while (option != 'q');
Upvotes: 2
Reputation: 182883
If you hit two keys, you'll read two characters. If you want to read characters, call getchar
. If you want to read lines, call some function that reads lines.
Upvotes: 1