在 C++ 中使用 cout 和 cin 循环错误?或者是
While loop bug with cout and cin in c++? or is it
所以基本上我是在制作一个聊天应用程序,然后我遇到了一个我无法修复的错误。为了不泄露我的源代码,这里有一个例子:
#include<iostream>
using namespace std;
int main()
{
while (true) {
string lol;
cout << "you say >> ";
cin >> lol;
}
return 0;
}
所以错误是当你在 cin 中键入 space 时
你输入:"hi lol" 它打印 "you say >>"
两倍多 space 你
重复 "you say >>" 次 我真的不明白为什么会这样。 Soemone 可以帮我吗?
这不是错误,那是 the way it works。
std::string
的 operator>>()
由空格分隔,因此您一次有效地得到一个词。
如果您想阅读整行,请使用 std::getline()
。
所以基本上我是在制作一个聊天应用程序,然后我遇到了一个我无法修复的错误。为了不泄露我的源代码,这里有一个例子:
#include<iostream>
using namespace std;
int main()
{
while (true) {
string lol;
cout << "you say >> ";
cin >> lol;
}
return 0;
}
所以错误是当你在 cin 中键入 space 时 你输入:"hi lol" 它打印 "you say >>" 两倍多 space 你 重复 "you say >>" 次 我真的不明白为什么会这样。 Soemone 可以帮我吗?
这不是错误,那是 the way it works。
std::string
的 operator>>()
由空格分隔,因此您一次有效地得到一个词。
如果您想阅读整行,请使用 std::getline()
。