本文介绍了如何再次请求输入c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题是如何询问用户他/她是否想再次输入。
ex。
你想再次计算吗?是或否。
My question is how I ask the user if he/she wants to input again.ex.do you want to calculate again? yes or no.
有人可以解释我做错了什么并修正错误。
Can someone explain what I am doing wrong and fix the error.
int main() {
}
int a;
cout << endl << "Write 1 for addition and 0 for substraction:" << endl;
cin >> a;
// addition
if (a == 1) {
cout << "You are now about to add two number together, ";
cout << "enter a number: " << endl;
int b;
cin >> b;
cout << "one more: " << endl;
int c;
cin >> c;
cout << b + c;
}
//Substraction
else if (a == 0) {
cout << "enter a number: " << endl;
int b;
cin >> b;
cout << "one more: " << endl;
int c;
cin >> c;
cout << b - c;
}
//If not 1 or 0 was called
else {
cout << "Text" << endl;
}
return 0;
}
推荐答案
int main()
{
string calculateagain = "yes";
do
{
//... Your Code
cout << "Do you want to calculate again? (yes/no) "
cin >> calculateagain;
} while(calculateagain != "no");
return 0;
}
需要注意的重要事项:
- 未选中此项,因此用户输入可能无效,但循环将再次运行。
- 您需要包含
< string>
使用字符串。
- This is not checked, so user input may be invalid, but the loop will run again.
- You need to include
<string>
to use strings.
简化的计算代码
int a;
cout << endl << "Write 1 for addition and 0 for substraction:" << endl;
cin >> a;
cout << "enter a number: " << endl;
int b;
cin >> b;
cout << "one more: " << endl;
int c;
cin >> c;
// addition
if (a == 1) {
cout << b + c;
}
//Substraction
else if (a == 0) {
cout << b - c;
}
//If not 1 or 0 was called
else {
cout << "Invalid number!\n";
continue; //restart the loop
}
此代码应在 do ... while
loop。
This code should be inside the do ... while
loop.
这篇关于如何再次请求输入c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!