简体   繁体   中英

C++ cin.ignore() skip loop

I created a for loop in my program that makes it so you have to press enter to continue. I did this Using cin.ignore(). This is the basic idea of the code that I am using.

for (int i = 0; i < 5; i++) {  // loop will do it for each player data
    cout << "Press Enter to Continue ";
    cin.ignore();
    system("cls");
    cout << "Playes Data" << endl;
}

This code works fine until the player decides to input something rather than just press enter. From what I understand, because the player inputted something, this means that there will be a buffer. You can get rid of the buffer from just using cin.ignore. This makes it so it skips an iteration and the player doesn't have to press enter to continue. I have just included a second cin.ignore, but I don't want them to have to press enter twice. Is there some way to use the second cin.ignore only if there is a buffer, or is there some other way to deal with this?

There is always a buffer. Calling std::cin.ignore() by itself, with no parameter values, simply skips the next char in the buffer, which may or may not be a '\\n' char from an ENTER press.

To skip everything in the buffer, up to the next ENTER press, use std::cin.ignore(std::numeric_limits<streamsize>::max(), '\\n') .

You can replace

cin.ignore();

with

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Where the second option will ignore all characters including the newline the enter key puts into the stream.

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