用cin处理空格并返回(换行符)

Handle whitespace and return (newline) with cin

本文关键字:换行符 返回 cin 处理 空格      更新时间:2023-10-16

如果程序希望用户输入文本(例如名称),如何处理空白和返回键?

char ch[100];
cout << "enter something: ";
cin >> ch;
cout << ch << endl;

如果用户

  1. 回车
  2. 空格+回车

像这样:

#include <iostream>
#include <string>
int main()
{
    for (std::string line; std::getline(std::cin, line); )
    {
        if (line.empty())
        {
            // handle blank input
        }
        std::cout << "You said: " << line << "n";
    }
}

这还不修剪空白;这可以通过在循环开始时修改line来轻松完成,例如使用此代码并在开始时添加trim(line);