C++程序要求我输入两次,即使变量第一次被分配

C++ Program requires me to input twice even though the variable gets assigned the first time

本文关键字:两次 变量 分配 第一次 程序 输入 C++      更新时间:2023-10-16

每次我尝试输入答案时,都需要我输入两次。即使 examScore1 在第一次就已经被分配了一个值,但它仍然需要我输入另一个值。我设计了该程序,以便如果输入任何不是数字的内容,它将输出错误消息,并要求用户再次输入一次,然后程序将完全结束。

 cout << "Please enter score for Exam 1: ";
        cin >> examScore1;
        if(!(cin >> examScore1)||!(examScore1 <= 100 || examScore1 >= 0))
        {
            cout << "Exam score cannot be less than 0 or more than 100" << endl;
            cout << "Please re-enter score for Exam 1: n";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), 'n');
            cin >> examScore1;
            if(!(cin >> examScore1)||!(examScore1 <= 100 || examScore1 >= 0))
            {
                cout << "nInvalid input entered. PROGRAM WILL END. Pleasen"
                     << "consult the user manual and restart the programn";
                validInput = false;
            }
        }

从您的代码中,我猜您希望用户输入的范围score从 0 到 100,如果用户输入无效的输入,您的程序只允许再输入一次,然后在用户再次输入无效的情况下退出。关于你关于为什么你的代码要求更多输入的问题,我将尝试在这里简要解释一下。

cout << "Please enter score for Exam 1: ";
cin >> examScore1;

在这里,您的代码要求输入,然后将其放入examScore1。然后

if(!(cin >> examScore1)||!(examScore1 <= 100 || examScore1 >= 0))

我想你想检查一下,但请稍等片刻。在第一句话中

!(cin >> examScore1)

你想要更多的输入,这就是为什么你的代码即使在你输入分数后也不断要求输入。如果您只想检查它,请像这样操作

if(examScore1 > 100 || examScore1 < 0){
    //Tell the user that the score is wrong
}

之后,您希望再次为用户提供输入的机会。在您的代码中

cout << "Exam score cannot be less than 0 or more than 100" << endl;
cout << "Please re-enter score for Exam 1: n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cin >> examScore1;
if(!(cin >> examScore1)||!(examScore1 <= 100 || examScore1 >= 0))
{
    cout << "nInvalid input entered. PROGRAM WILL END. Pleasen"
         << "consult the user manual and restart the programn";
    validInput = false;
}

哇,伙计,冷静点:)。你只是想让他们输入另一个。只是好好地问他们。

cout << "Please input score in range (0-100)";
cin >> examScore1;
if(examScore1 > 100 || examScore1 < 0){
    cout << "Wow dude, read the doc please";
}

最后结束,你的代码看起来更像这个

cout << "Please enter score for Exam 1: ";
cin >> examScore1;
if(examScore1 > 100 || examScore1 < 0){
    cout << "Please input score in range (0-100)";
    cin >> examScore1;
    if(examScore1 > 100 || examScore1 < 0){
        cout << "Wow dude, read the doc please";
    }
}

您的问题是您多次要求 cin 。首先,您将值 cin>>考试分数1;那里没有问题。但是在你的 if 中,你写 if(!(cin>>考试成绩1))这实质上是要求计算机再次从控制台读取值。正确的方法是 if(!examScore1),

另外,你想用if(!(cin>> examScore1))?