简体   繁体   English

C++ cin.ignore() 跳过循环

[英]C++ cin.ignore() skip loop

I created a for loop in my program that makes it so you have to press enter to continue.我在我的程序中创建了一个 for 循环,因此您必须按 Enter 才能继续。 I did this Using cin.ignore().我使用 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.这段代码可以正常工作,直到玩家决定输入内容而不是直接按 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.您可以仅使用 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.我刚刚包含了第二个 cin.ignore,但我不希望他们必须按 Enter 两次。 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?是否有某种方法可以仅在有缓冲区时才使用第二个 cin.ignore ,或者是否有其他方法来处理这个问题?

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. std::cin.ignore()调用std::cin.ignore() ,没有参数值,只是跳过缓冲区中的下一个字符,它可能是也可能不是来自ENTER键的'\\n'字符。

To skip everything in the buffer, up to the next ENTER press, use std::cin.ignore(std::numeric_limits<streamsize>::max(), '\\n') .要跳过缓冲区中的所有内容,直到下一次ENTER键,请使用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.第二个选项将忽略包括回车键放入流中的换行符在内的所有字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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