简体   繁体   中英

“Enter a character to quit” program in C

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?

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 :)

"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');
}

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');

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.

getchar()函数首先从缓冲区读取。如果缓冲区为空,则从标准输入(即屏幕)读取。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM