在 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)
感谢您的时间。
你想要的是std::cin::ignore. 使用
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Run Code Online (Sandbox Code Playgroud)
您将传递流中的所有字符,直到遇到换行符,从而丢弃当前行。
您可以将 更改'\n'为任何其他字符,并ignore会一直读取直到遇到该字符。例如,使用' ', 将允许您跳过当前的“单词”。
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |