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

404*_*und 1 c++

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

char c = getchar(); // get a character
getchar(); // detect pressing the enter key
Run Code Online (Sandbox Code Playgroud)

在 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
Run Code Online (Sandbox Code Playgroud)

感谢您的时间。

Nat*_*ica 6

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

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Run Code Online (Sandbox Code Playgroud)

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

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

  • @404NameNotFound 好消息是你可以将其包装在像 `voidignore_line() { std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); 这样的函数中 }` 现在在你的代码中,你只需编写 `ignore_line();`。 (2认同)