如何再次请求输入c ++

时间:2016-08-28 16:19:43

标签: c++ if-statement input cin

我的问题是如何询问用户他/她是否想再次输入。 恩。 你想再计算一下吗?是或否。

有人可以解释我做错了什么并修正错误。

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 个答案:

答案 0 :(得分: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;
}

需要注意的重要事项:

  1. 未选中此选项,因此用户输入可能无效,但循环将再次运行。
  2. 您需要包含<string>才能使用字符串。
  3. 简化的计算代码

    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循环内。