Home > Blockchain >  While loop executes twice in a row
While loop executes twice in a row

Time:03-24

I have a while loop with a cin.get() prompt.

    char ch;
while (true)
{
    cout<<"Please type in a character:"<<endl;
    cin.get(ch);
    cout<<"ch = "<<ch<<endl; }

Once the character is entered and "enter" pressed, the loop executes twice. Here is the output:

Please type in a character:
A
ch = A
Please type in a character:
ch = 

Please type in a character:

How do I get rid of that?

Thanks

CodePudding user response:

On the 1st iteration, get() will return the user's character, but the Enter (\n) will still be in the input buffer. On the 2nd iteration, get() will then return that \n. And then, on the 3rd iteration, get() will block waiting for the user to enter a new character.

You need to discard that \n from the input buffer, eg:

char ch;
do
{
    cout << "Please type in a character:" << endl;
    cin.get(ch);
    cout << "ch = " << ch << endl;
    if ((ch != '\n') && (cin.peek() == '\n'))
        cin.ignore();
}
while (true);

Or, simply use operator>> instead, which skips leading whitespace, including \n, eg:

char ch;
do
{
    cout << "Please type in a character:" << endl;
    cin >> ch;
    cout << "ch = " << ch << endl;
}
while (true);

CodePudding user response:

use

cin.ignore()

after

cin.get()
  •  Tags:  
  • c
  • Related