C++中的换行符(回车键)

new line character(enter key) in C++

我想写一个程序,在每句话之后做一个处理。 像这样:

char letter;
while(std::cin >> letter)
{
  if(letter == '\n')
  { 
    // here do the process and show the results.
  }

}

我想要当用户按下回车键时(意味着句子结束) 所以我们做一个过程然后在显示一些结果后用户可以输入新的短语但是行 如果(字母=='\n') 不像我预期的那样工作。 请告诉我该怎么做。 谢谢。

您想使用 getline() probably, because std::cin 将在空格处停止:

#include <iostream>

int main()
{
    std::string x;
    while(x != "stop") //something to stop
    {
        std::cout << "Your input : ";
        std::getline(std::cin, x);
        std::cout << "Output : " << x << "\n"; //Do other stuff here, probably
    }
    std::cout << "Stopped";
}

结果:

Your input : test1
Output : test1
Your input : abc def ghi
Output : abc def ghi
Your input : stop
Output : stop
Stopped

如果我理解你的问题并且你想捕获 '\n' 字符,那么你需要使用 std::cin.get(letter) 而不是 std::cin >> letter; 如评论中所述,>> 运算符将丢弃前导空格,因此 stdin 中剩余的 '\n' 在下一次循环迭代中将被忽略。

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";
    }
}

将在每次按下 Enter 后生成 "got newline" 输出。