我想写一个程序在每句话后面做一个处理。像这样:
char letter;
while(std::cin >> letter)
{
if(letter == '\n')
{
// here do the process and show the results.
}
}
Run Code Online (Sandbox Code Playgroud)
我希望当用户按下回车键(意味着句子已完成)时,我们会执行一个过程,然后在显示一些结果后,用户可以输入新的短语,但 if(letter == '\n') 行不会没有按我的预期工作。请告诉我如何做到这一点。谢谢。
如果我理解你的问题并且你想捕获该'\n'字符,那么你需要使用std::cin.get(letter)而不是std::cin >> letter;如注释中所述,该>>运算符将丢弃前导空格,因此在下一次循环迭代中将忽略'\n'左侧。stdin
std::cin.get()是原始读取,将读取 中的每个字符stdin。请参阅std::basic_istream::get例如:
#include <iostream>
int main (void) {
char letter;
while (std::cin.get(letter)) {
if (letter == '\n')
std::cout << "got newline\n";
}
}
Run Code Online (Sandbox Code Playgroud)
每次按下"got newline"后都会产生输出。Enter