how to ask for input again c++

2019-09-21 15:06发布

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

1条回答
Deceive 欺骗
2楼-- · 2019-09-21 15:56
int main()
{
    string calculateagain = "yes";
    do
    { 
        //... Your Code
        cout << "Do you want to calculate again? (yes/no) "
        cin >> calculateagain;
    } while(calculateagain != "no");
    return 0;
}

Important things to note:

  1. This is not checked, so user input may be invalid, but the loop will run again.
  2. You need to include <string> to use strings.

Simplified Calculation Code

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

}

This code should be inside the do ... while loop.

查看更多
登录 后发表回答