如何再次请求输入 C++
how to ask for input again c++
我的问题是如何询问用户 he/she 是否要再次输入。
前任。
你想重新计算吗?是或否。
谁能解释一下我做错了什么并修复错误。
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>
才能使用字符串。
简化计算代码
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
循环内。
我的问题是如何询问用户 he/she 是否要再次输入。 前任。 你想重新计算吗?是或否。
谁能解释一下我做错了什么并修复错误。
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>
才能使用字符串。
简化计算代码
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
循环内。