未通过类型检查

时间:2015-10-25 23:24:15

标签: c++

我想做一个"闰年"程序作为实践。
这是我的代码:

List<Set<Integer>> listOfSets = new ArrayList<>(allSets);
Collections.sort(listOfSets, <your comparator above>);
System.out.println(listOfSets).

但我不能在检查你输入的内容是否为#include <iostream> #include <string> int main (){ int year; std::string flag01; do { std::cout << "Input year: "; std::cin >> year; //check for int input while (std::cin.fail()){ std::cout << "Oops..." << std::endl << "I failed to get a year..." << std::endl << "Try again?"; std::cin.clear(); std::cin >> year; } if (year % 4 == 0 && year % 100 != 0 && year != 0) std::cout << "the year " << year << " is a leap year.\n"; else std::cout << "the year " << year << " is not a leap year.\n"; std::cout << "Would you like to input another? yes / no \n"; do { std::cin >> flag01; if (flag01 != "yes" && flag01 != "no") std::cout << "please only insert yes or no\n"; } while (flag01 != "no" && flag01 != "yes"); } while (flag01 != "no"); return 0; } 的情况下制作部分。我不知道自己做错了什么 当我运行它并输入intchar时,它会进入无限循环并继续打印第11行。

我在这里看到stringstd::cin.failChecking input value is an integer

请帮助和谢谢。

1 个答案:

答案 0 :(得分:0)

您正在清除错误状态,但导致错误的数据仍在流中。用忽略来清除它......

    std::cout << "Oops..." << std::endl << "I failed to get a year..." << std::endl << "Try again?";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //extract all characters until /n
    std::cin >> year;

包含std :: numeric_limits的标头限制。

#include <limits>