【问题标题】:cin.sync and clear are not working?cin.sync 和 clear 不起作用?
【发布时间】:2014-02-16 10:45:43
【问题描述】:
        while(cout << "How many elements do you want: " && !(cin >> el))
        {
            cin.sync();
            cin.clear();
            cout << " Invalid input!\n";
        }

el 是一个 int,当我输入一个字符时,循环会无限循环。 我按照 SO 中的一篇帖子修复了错误的输入,但它不起作用,它会无限循环打印“你想要多少元素:无效输入!” 我也试过 ignore(10000, "\n") ,但还是不行……

【问题讨论】:

    标签: c++ cin


    【解决方案1】:

    从流中读取时发生错误时,会设置错误标志,并且在清除错误标志之前无法进行更多读取。

    这就是你得到一个无限循环的原因。

    改为使用:

    cin.clear();  // clears the error flags  
    // this line discards all the input waiting in the stream
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    

    【讨论】:

      【解决方案2】:

      cin.sync() 之前执行cin.clear()。它对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-03
        • 1970-01-01
        • 1970-01-01
        • 2019-12-03
        • 2012-05-22
        • 2020-07-17
        • 2015-06-04
        • 2021-11-25
        相关资源
        最近更新 更多