【发布时间】:2023-03-04 07:55:09
【问题描述】:
我正在尝试在 C++ 中练习我的输入验证。当要求用户输入数字或字符串时,如何让程序验证用户输入? 这是我的代码示例。
public:
void CreateProduct() {
inputProduct:
system("cls");
cout << "\n\n\n\n\n\n\n\t\t\t\tPLEASE PROVIDE ACCURATE INFORMATION";
cout << "\n\n\t\tPRODUCT NUMBER: ";
cin >> ProductNumber;
if (!cin) {
cout << "\nPlease provide an integer";
cin.clear();
cin.end;
goto inputProduct;
//when enter a string i should enter this if statement and exit
// to be asked for another entry but am getting stuck in a loop.
}
system("cls");
cout << "\n\n\n\n\n\n\n\t\t\t\tPRODUCT NAME: ";
cin >> ProductName;
system("cls");
cout << "\n\n\n\n\n\n\n\t\t\t\tPRICE: ";
cin >> Price;
system("cls");
}
请帮助我理解这个输入验证。
【问题讨论】:
-
有什么特别不明白的地方?
-
如果它是一个整数条目,它不应该接受文本或字符串。
-
你的意思是如果你输入一个整数,它不会跳过
if (!cin) { ...? -
它会跳过,但如果它不是整数,它就会陷入循环。
-
@WillieMwewa 摆脱
goto并使用do - while循环。
标签: c++ validation input console