有没有办法“丢弃”std::getline()的输出参数?

在 C 中,getchar()可用于从输入缓冲区 ( char c = getchar();) 中获取字符,但也可以通过忽略返回值将该函数用作按键检测器。

char c = getchar(); // get a character
getchar(); // detect pressing the enter key

在 C++ 中,我可以std::string in; std::getline(std::cin, in);用来获取输入。std::getline()似乎只接受std::string其第二个参数的引用。有什么我可以做的,以避免必须声明一个虚拟变量?

std::string in; // dummy variable
std::getline(std::cin, in); // discard the input anyway

感谢您的时间。

回答

你想要的是std::cin::ignore. 使用

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

您将传递流中的所有字符,直到遇到换行符,从而丢弃当前行。

您可以将 更改'n'为任何其他字符,并ignore会一直读取直到遇到该字符。例如,使用' ', 将允许您跳过当前的“单词”。

  • @404NameNotFound Good news is you can wrap this in a function like `void ignore_line() { std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n'); }` and now in your code, you just write `ignore_line();`.

以上是有没有办法“丢弃”std::getline()的输出参数?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>