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

时间:2018-08-26 07:46:12

标签: c++

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。 无效的输入是任何特殊字符,字母和任何形式的负数。

2 个答案:

答案 0 :(得分:1)

您可以只使用while循环。

它可能会这样:

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

答案 1 :(得分:1)

当前,您的代码不包含任何可打印错误消息的内容。不过,您似乎已经在处理错误情况,因此添加它并不难。

如果您像这样在else循环中更改for的大小写,它将起作用:

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;
    }

但是,您应该考虑重构代码以防止重复。例如,如果您在单独的函数中验证输入,则可以在一个清晰的位置进行错误处理,而不是现在拥有重复项。