how to ask for input again c++

▼魔方 西西 提交于 2019-12-13 09:26:47

问题


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:


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.



来源:https://stackoverflow.com/questions/39193327/how-to-ask-for-input-again-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!