【问题标题】:If "std::cin" 's input was incorrect then it will crash but the rest of program will work [duplicate]如果 "std::cin" 的输入不正确,那么它将崩溃,但程序的其余部分将工作 [重复]
【发布时间】:2018-11-06 01:42:06
【问题描述】:

喜欢下面的代码:

int count = 0;
std::cin >> count_of_emploies;
for (int i = 0; i < 11 && (count <= 1 || count >= 100); i++) {
    std::cout << "enter again.";
    std::cin >> count;
    if (i > 9) return 0;
}

但是当输入类似于“asdf”时,此代码会导致所有 std::cin 粉碎,程序的其他部分几乎可以工作,但无需等待用户输入。

【问题讨论】:

    标签: c++


    【解决方案1】:

    当输入类似于“asdf”时,此代码会导致所有 std::cin 粉碎

    这是因为收到了“错误”输入。 要忽略这一点并继续,您必须

    a) 清除流错误标志std::cin.clear()

    b) 忽略输入缓冲区中的最大可能字符,直到换行符使用std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 2019-05-30
      • 1970-01-01
      相关资源
      最近更新 更多