【发布时间】:2018-11-26 01:56:09
【问题描述】:
我试图只允许输入整数
应该拒绝:
- 5 小时
- 3.4
- 3.gh
- 3.0
- htr
应该接受:
- -5
- 0
- 78
当前代码
int getIntInput() {
int userInput;
while (true) {
std::cout << "> ";
std::cin >> userInput;
std::cout << std::flush;
if (std::cin.fail()) {
std::string cinBuffer;
std::cin.clear();
std::getline(std::cin, cinBuffer);
continue;
}
break;
}
return userInput;
}
更新代码
问题:
-
接受除“htr”(无数字)之外的所有拒绝
int getIntInput() { std::string rawInput; int parsedinput; while (true) { std::cout << "> "; std::getline(std::cin, rawInput); std::cout << std::flush; try { parsedinput = std::stoi(rawInput); } catch (std::invalid_argument & e) { continue; } catch (std::out_of_range & e) { continue; } break; } return parsedinput; }
完成的代码
-
只接受带有可选参数的整数,这将允许 要接受或拒绝的负数。
int getIntInput(bool allowNegatives = true) { bool validIntInput; std::string rawInput; int parsedinput; while (true) { validIntInput = true; // Grabs the entire input line std::cout << "> "; std::getline(std::cin, rawInput); std::cout << std::flush; for (int i = 0; i < rawInput.length(); i++) { // Checks to see if all digits are a number as well as to see if the number is a negative number if (!isdigit(rawInput[i]) && !(allowNegatives && i == 0 && rawInput[i] == '-')) { validIntInput = false; break; } } if (!validIntInput) { continue; } else { try { // Try parse the string to an int parsedinput = std::stoi(rawInput); // Catch all possible exceptions, another input will be required } catch (...) { continue; } // If the code reaches here then the string has been parsed to an int break; } } return parsedinput;}
【问题讨论】:
-
您有什么要求?我不知道你期望会发生什么。最好提供几个用户输入和预期结果的示例。
-
只获取整数作为输入,如果输入了 4.5 等值,则不应接受该值,应输入另一个输入