【问题标题】:Cin: wait for <ENTER>. Two continues cin.ignore do not workCin:等待 <ENTER>。两个继续 cin.ignore 不起作用
【发布时间】:2014-06-30 18:28:53
【问题描述】:

代码如下:

cout << "Press <ENTER> when you are ready to procceed..." << endl;
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
cin.ignore(std::numeric_limits<streamsize>::max());
cin.clear();
...
cout << "Insert " << nominal << " rubbles into money acceptor and press <ENTER>" << endl;
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
cin.ignore(std::numeric_limits<streamsize>::max());
cin.clear();

第一次等待,第二次直接扔掉,没有任何停顿。

我尝试只使用 cin.ignore(std::numeric_limits::max(),'\n');或 cin.get() 或 cin.ignore() 或 getchar()。没有任何效果。

我什至试图让用户输入一个数字:

{cout << "eof: " << cin.eof(); int num; cin >> num; cout << "eof: " << cin.eof(); }

这第二次也不行!它在第二次调用时从 cin 读取“32767”。 和输出:

eof: 0
eof: 1

【问题讨论】:

    标签: c++ cin


    【解决方案1】:

    我不太清楚你想做什么,或者为什么。但是,我编写了这个简单的测试应用程序,对我来说效果很好:

    #include <iostream>
    #include <limits>
    
    int main()
    {
        std::cout << "Press enter to start\n";
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        std::cout << "Press enter again to begin data entry\n";
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    
        int i, j;
    
        std::cout << "Enter a value for i\n";
        std::cin >> i;
        // skip any trailing characters after the number the user entered
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        std::cout << "Enter a value for j\n";
        std::cin >> j;
        // skip any trailing characters after the number the user entered
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    
        std::cout << "i was " << i << ", j was " << j << "\n";
    
        std::cout << "Press enter to continue\n";
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        std::cout << "Press enter again to exit\n";
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    
        return 0;
    }
    

    离开代码中的cin.ignore(std::numeric_limits&lt;streamsize&gt;::max()); 行会迫使我按回车键(触发“忽略\n 代码),然后按control-D 发送EOF 以触发第二个ignore调用。我无法复制您的“它会直接通过它而没有任何暂停” 条件。

    此代码在 GCC 4.7.2 和 VS2013 Express 下正确构建和运行。

    【讨论】:

    • 您的代码有效。我会遇到由 SIGIO sygnal 引起的问题吗?当我的第二个 cin.ignore() 正在等待“\n”时,此类信号会不断发送。我该如何克服这个问题?
    • @Arks 嗯。突然间,这听起来像是一个非常不同的问题!我怀疑答案是使用每线程信号屏蔽,并在单独的工作线程中处理 SIGIO。但是,我不能真正建议您如何做到这一点。你或许应该问一个新问题?
    • 我先研究一下per-thread信号屏蔽。然后,如果需要,我会提出一个问题。谢谢。
    【解决方案2】:

    尝试:

    cin.sync()
    

    也许它会起作用......

    【讨论】:

    • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方发表评论 - 您可以随时评论自己的帖子,一旦您有足够的reputation,您就可以comment on any post
    • 是的,我愿意。但我做不到……我需要 50 个声望。
    猜你喜欢
    • 2017-05-03
    • 2012-12-09
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 2016-08-16
    相关资源
    最近更新 更多