cin notn n over to等待我的输入,即使我用cin.sync()和cin.clear()将其重置

发布于 2025-01-26 07:45:22 字数 925 浏览 3 评论 0原文

今天,我开始从事一个很大的项目,发现这个问题从未发现。我一直用来用Sync()和clear()顺序使用用法来重置CIN流。但是,在我更改了编译器(一个月前,我从独立的mingw转换为MINGW通过MSYS2)以在STD库中包含文件系统,似乎这种组合不再可用。现在我问两个不同的问题:

  1. 有人知道为什么吗? (我正在使用GCC 11.2.0,刚刚检查了我的CMD)
  2. 如何解决此问题?

这是示例代码:

#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:

  1. Does anyone knows why exactly? (I'm using gcc 11.2.0, just checked on my CMD)
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文