c ++中cin的功能

wya*_*att 1 c++

我对以下函数的结果有点困惑:

int main() {
string command;
while(1) {
    cin >> command;

    if(command == "end")
            return 0;
    else
            cout << "Could you repeat the command?" << endl;
}

return 0;
Run Code Online (Sandbox Code Playgroud)

}

首先 - 输出行("你能......")对输入中的每个单词重复一次(存储在命令中).据我所知,它应该只能为每个循环实例发生一次.

此外,当行'if(command =="end")'更改为'if(command =="that all")时,它永远不会触发.一点点测试表明从命令中删除了所有空格.

有人可以向我解释这里发生了什么吗?

谢谢

小智 5

格式化的输入运算符>>()从输入中读取空格分隔的标记.如果要读取整行,请使用getline()函数:

string command;
getline( cin, command );
Run Code Online (Sandbox Code Playgroud)