C++ if 语句不解析空格

C++ if statement not parsing whitespace

我在 C++ 控制台应用程序中的 if 语句不起作用:

string line;
cin >> line;

if (line == "a b"){
    cout << "lalala";
}

当我键入 "a b" 时没有任何反应。
如果我使用 if (line == "ab") 并输入 ab 就可以了。

std::cin 读取由白色-space 分隔。因此,当您阅读 cin >> line 时,您只是在阅读 "a b" 中的 "a"。使用std::getline(std::cin, line)读取整行,包括white-space(不是'\n').

顺便说一句,您可以通过使用调试器查看变量或打印变量来轻松发现此问题。在发布问题之前调试您的代码。

注意:std::cin 我的意思是 operator>>,它有很多重载,作为非成员和 istream 成员。采用 std::string 的重载读取由 white-space.

分隔

因为读到空格结束,所以这里line就是"a"

operator>>(std::basic_string)

until one of the following conditions becomes true:

std::isspace(c,is.getloc()) is true for the next character c in is (this whitespace character remains in the input stream).