[英]Validating Integer Input in C++
我正在尝试验证输入,仅接受整数,并且它对于 4 之后的字母和小数点工作正常。例如,如果我输入 1.22,它将只读取第一个并进入不定式循环,但是当我输入数字时,更大的是什么比4,例如5.55它工作得很好,我该如何解决这个问题? 谢谢并感谢您的帮助!
void Furniture::getSelection()
{
do {
cout << "\nWhich object would you like to measure:\n"
<< "1.Table\n"
<< "2.Stool\n"
<< "3.Bookshelf\n"
<< "4.Exit\n" << endl;
while(!(cin >> choice)) {
cerr << "The format is incorrect!" << endl;
cin.clear();
cin.ignore(132, '\n');
}
while(choice != 1 && choice != 2 && choice != 3 && choice != 4) {
cerr << "Invalid Input!!Try again\n" << endl;
break;
}
} while(choice != 1 && choice != 2 && choice != 3 && choice != 4);
这是一个简短的示例程序,可以确保 ASCII 输入介于 1 和 4 之间。
#include <exception>
#include <iostream>
#include <string>
int menu_selection() {
int choice = 0;
std::string input;
do {
std::cout << "\nWhich object would you like to measure:\n"
<< "1. Table\n"
<< "2. Stool\n"
<< "3. Bookshelf\n"
<< "4. Exit\n\n";
std::getline(std::cin, input);
// Handles the input of strings
std::string::size_type loc = 0;
try {
choice = std::stoi(input, &loc);
} catch (std::exception& e) { // std::stoi throws two exceptions, no need
// to distinguish
std::cerr << "Invalid input!\n";
continue;
}
// Handles decimal numbers
if (loc != input.length()) {
choice = 0;
}
// Handles the valid range
if (choice < 1 || choice > 4) {
std::cerr << "Invalid Input! Try again\n\n";
}
} while (choice < 1 || choice > 4);
return choice;
}
int main() {
int selection = menu_selection();
std::cout << "You chose " << selection << ".\n";
}
此代码不属于您的家具类。 选择家具不是“被”家具。 菜单和选择应该在课外,然后你对你的家具类进行适当的调用。
另一种思考方式是与其他开发人员共享家具类。 也许他们不关心测量家具。 但是现在您已经通过将其包含在类中来强制对它们进行这种测量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.