如何向用户显示特定错误,要求他/她使用循环再次提供输入?
How to display a specific error to the user, requiring him/her to provide input again using a loop?
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;
}
但是,您应该考虑稍微重构一下代码以防止一些重复。例如,如果您在单独的函数中验证输入,则可以有一个明确的错误处理位置,而不是现在的重复。
相关文章:
- 正在尝试了解输入验证循环
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 通过for循环使用用户输入填充列表
- 计算用户使用循环输入的整数数量
- 从文件循环输入的更合适方法?
- 实现递归函数,避免由 C++ 中 include 的循环调用(没有 #pragma 一次)引起的无限循环输入
- 我应该使用 DeviceContext 函数在管道中循环输入还是通过创建来输入
- 如何在代码中插入循环输入
- 循环输入数据
- 为循环输入并中断C++:至少10次迭代且没有空字符串
- 第一次通过循环输入空字符串?(c++)
- 使用while循环输入的小问题
- 下次不会让我通过 while (true) 循环输入信息
- 我如何让一个数组来存储用户在 C 中使用 do-while 循环输入的最多 10 个元素
- C++循环 - 输入整数,直到用户退出
- 将随机数插入到数组中,其中每个值都是通过 for 循环输入的
- 从文件循环输入流
- 这个函数请求用户通过循环输入文件名的错误在哪里?
- cin.当循环输入时失败
- 如何添加循环输入文件的结果