我正在尝试验证输入,只接受整数,并且它对4之后的字母和小数点都很好。例如,如果我输入1.22,它将只读取数字1并进入不定式循环,但当我输入大于4的数字时,例如5.55,它运行良好,那么我如何解决这个问题?感谢您的帮助!
void Furniture::getSelection()
{
do {
cout << "nWhich object would you like to measure:n"
<< "1.Tablen"
<< "2.Stooln"
<< "3.Bookshelfn"
<< "4.Exitn" << 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 againn" << endl;
break;
}
} while(choice != 1 && choice != 2 && choice != 3 && choice != 4);
这里有一个简短的示例程序,可以确保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. Tablen"
<< "2. Stooln"
<< "3. Bookshelfn"
<< "4. Exitnn";
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 againnn";
}
} while (choice < 1 || choice > 4);
return choice;
}
int main() {
int selection = menu_selection();
std::cout << "You chose " << selection << ".n";
}
此代码不属于您的家具类。选择家具不是"成为"家具。菜单和选择应该在类之外,然后您对家具类进行适当的调用。
另一种思考方式是与其他开发人员共享Furniture类。也许他们不在乎测量家具。但现在你把它包括在课堂上,迫使他们进行这种测量。