我正在尝试验证输入,只接受整数,它对4之后的字母和小数点工作得很好。例如,如果我输入1.22,它将只读取数字1并进入无限循环,但当我输入大于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);发布于 2020-03-19 21:56:16
下面是一个简短的示例程序,可以确保ASCII输入介于1和4之间(包括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";
}此代码不属于您的家具类。选择家具并不是“做”家具。菜单和选择应该在类之外,然后对您的家具类进行适当的调用。
考虑这一点的另一种方式是与其他开发人员共享家具类。也许他们不关心测量家具的尺寸。但现在,您通过将其包含在类中,将此度量强加给了他们。
https://stackoverflow.com/questions/60758281
复制相似问题