gpt4 book ai didi

c++ - 接受用户输入时的错误处理第 2 部分

转载 作者:行者123 更新时间:2023-11-30 03:12:49 25 4
gpt4 key购买 nike

我之前提过一个问题: 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

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

最佳答案

在您的 displayMainMenu() 函数中,不是读取 char,而是读取字符串。丢弃(警告)任何长度超过一个字符的输入。

你可以使用

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

代替

cin >> mainMenuChoice;

为了读取字符串。

关于c++ - 接受用户输入时的错误处理第 2 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/236436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com