cin notn n over to等待我的输入,即使我用cin.sync()和cin.clear()将其重置
今天,我开始从事一个很大的项目,发现这个问题从未发现。我一直用来用Sync()和clear()顺序使用用法来重置CIN流。但是,在我更改了编译器(一个月前,我从独立的mingw转换为MINGW通过MSYS2)以在STD库中包含文件系统,似乎这种组合不再可用。现在我问两个不同的问题:
- 有人知道为什么吗? (我正在使用GCC 11.2.0,刚刚检查了我的CMD)
- 如何解决此问题?
这是示例代码:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int number;
string s;
cout << "insert a number" << endl;
cin >> number;
cin.sync();
cin.clear();
cout << "Now insert a string" << endl;
getline(cin, s);
cout << "This is your number: " << number << endl;
cout << "This is your string: " << s << endl;
}
这是终端:
insert a number
8
Now insert a string
This is your number: 8
This is your string:
显然,您可以看到它不在等我的输入,我认为它可以作为字符串的字符进入。这就是为什么它打印似乎一无所有的原因(简直就是'\ n')
Today i started working on a quite big project and found this problem I've never found. I always used to reset the cin stream with the usage in sequence of sync() and clear(). But after i changed my compiler (a month ago i switched from standalone minGW to minGW through msys2) to have filesystem included in the std library, it seems this combination doesn't work anymore. Now I'm asking 2 different questions:
- Does anyone knows why exactly? (I'm using gcc 11.2.0, just checked on my CMD)
- How can I solve this problem?
Here's the example code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int number;
string s;
cout << "insert a number" << endl;
cin >> number;
cin.sync();
cin.clear();
cout << "Now insert a string" << endl;
getline(cin, s);
cout << "This is your number: " << number << endl;
cout << "This is your string: " << s << endl;
}
And here's the terminal:
insert a number
8
Now insert a string
This is your number: 8
This is your string:
Obviously as you can see it doesn't wait for my input and i think it gets my enter as a char for the string. That's why it prints what seems to be nothing (it's simply '\n')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论