错误处理 - 当用户输入第2部分时

时间:2008-10-25 13:53:46

标签: c++

我先前提出了一个问题: error handling when taking user input

我提出了建议的更改:

char displayMainMenu()
{
char mainMenuChoice;
cout << "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; 
cout << "\n <r>  Give new coefficients"; 
cout << "\n <c>  Calculate equations solutions"; 
cout << "\n <t>  Terminate the program";
cout<<"Enter choice : ";
cin>>mainMenuChoice;
return mainMenuChoice;
}

int main()
{
bool done = false;
while(!done)
{
    char choice = displayMainMenu();  
    switch(tolower(choice))
    {
        case 'r':
                cout<<"Entered case 'r'";
                break;
        case 'c':
                cout<<"Entered case 'c'";
                break;  
        case 't':
                cout<<"Entered case 't'";                   
                break;
        default:
                cout<<"Invalid choice! Try again"<<endl;   
    }
}
return 0;
}

新问题是,如果用户错误地输入,请说“ter”我得到以下内容:(:

Quadratic equation: a*X^2 + b*X + c = 0 main menu:   
 <r>  Give new coefficients 
 <c>  Calculate equations solutions  
 <t>  Terminate the program 
Enter choice : ter 
Entered case 't'

Quadratic equation: a*X^2 + b*X + c = 0 main menu:  
 <r>  Give new coefficients 
 <c>  Calculate equations solutions  
 <t>  Terminate the program 
Enter choice : Invalid choice! Try again

Quadratic equation: a*X^2 + b*X + c = 0 main menu:  
 <r>  Give new coefficients 
 <c>  Calculate equations solutions  
 <t>  Terminate the program 
Enter choice : Invalid choice! Try again

我怎么能避免这种情况发生?

2 个答案:

答案 0 :(得分:2)

displayMainMenu()函数中,不是阅读char,而是读取字符串。抛出(带警告)任何长度超过一个字符的输入。

您可以使用

char str[101]
std::cin.getline(str, 101);

取代

cin >> mainMenuChoice;

以便读取字符串。

答案 1 :(得分:1)

试试这个:

string displayMainMenu()
{
    string mainMenuChoice;
    cout << "\nQuadratic equation: a*X^2 + b*X + c = 0 main menu: "; 
    cout << "\n <r>  Give new coefficients"; 
    cout << "\n <c>  Calculate equations solutions"; 
    cout << "\n <t>  Terminate the program";
    cout << "\nEnter choice : ";
    getline(cin, mainMenuChoice);
    return mainMenuChoice;
}

int main()
{
    bool done = false;
    while(!done)
    {
        string choice = displayMainMenu();
        if (choice.size() > 1 || choice.size() < 0)
            cout<<"Invalid choice! Try again"<<endl;

        switch(tolower(choice[0]))
        {
        case 'r':
            cout<<"Entered case 'r'";
            break;
        case 'c':
            cout<<"Entered case 'c'";
            break;  
        case 't':
            cout<<"Entered case 't'";
            break;
        default:
            cout<<"Invalid choice! Try again"<<endl;   
        }
    }
    return 0;
}

使用getline(istream,string&amp;)一次读一整行(不包括eol)。检查它是否合适,然后只查看第一个字符。