如何向用户显示特定错误,要求他/她使用循环再次提供输入?

How to display a specific error to the user, requiring him/her to provide input again using a loop?

本文关键字:循环 输入 显示 用户 错误      更新时间:2023-10-16
using namespace std;
int main(){
// Variable declarations
string hours = "";
double empHours = 0;
bool cont = true;
do{
// Get input of how much employee worked in a week.
cout << "Enter hours worked in a week: " ;
getline(cin, hours);
// Convert the input using string stream for easier validation.
stringstream hours_input(hours);
for(int i = 0; i <= hours[i]; i++)
// Check if input contains any alphabets e.g 90abc, if yes than repeat loop and ask user for input again.
if(isalpha(hours[i]))
cont = true;
// If the input successfully converts to double type
else if(hours_input >> empHours)
// Check if values are values >= 0, if yes than exit the loop
if(empHours >= 0){
hours_input >> empHours;    // Assign value to empHours and exit loop
cont = false;
}
//  Check if input contains special characters or any other form of bad input, if yes than repeat loop and ask user for input again.    
else    
cont = true;
}while(cont);
cout << "Value is: " << empHours << endl;
return 0;
}

这就是我到目前为止得到的。我只是不确定如何显示错误"这不是一个有效的选项,请重试"并再次要求输入。但是,该代码可以正常工作,而不是显示提到的错误,它显示"输入一周内的工作小时数:"。

简单地说,继续循环错误"这不是一个有效的选项,请重试"并要求输入,直到提供有效的输入。

有效输入应为任意整数或浮点数number >= 0。 无效输入是任何特殊字符、字母和任何形式的负数。

你可以只使用while循环。

它可以是这样的:

while(true){
cin>>foo;
if(check if foo is a valid input){
break; //if the input is valid
}
cout<<"error, try again";
}

目前,您的代码不包含任何用于打印错误消息的内容。不过,您似乎已经在处理错误场景,因此添加它并不难。

如果您像这样更改for循环中的else大小写,它应该可以工作:

for(int i = 0; i <= hours[i]; i++)
// Check if input contains any alphabets e.g 90abc, if yes than repeat loop and ask user for input again.
if(isalpha(hours[i]))
{
cout << "That is not a valid option, please try again." << endl;
cont = true;
}
// If the input successfully converts to double type
else if(hours_input >> empHours)
// Check if values are values >= 0, if yes than exit the loop
if(empHours >= 0){
hours_input >> empHours;    // Assign value to empHours and exit loop
cont = false;
}
//  Check if input contains special characters or any other form of bad input, if yes than repeat loop and ask user for input again.    
else
{
cout << "That is not a valid option, please try again." << endl;
cont = true;
}

但是,您应该考虑稍微重构一下代码以防止一些重复。例如,如果您在单独的函数中验证输入,则可以有一个明确的错误处理位置,而不是现在的重复。