C++程序要求我输入两次,即使变量第一次被分配
C++ Program requires me to input twice even though the variable gets assigned the first time
每次我尝试输入答案时,都需要我输入两次。即使 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))?
相关文章:
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 调用一个小函数两次(例如在if条件和主体中)比将结果存储在局部变量中更可取
- "... already defined in *.obj"但我没有在同一范围内两次定义任何变量
- 为什么将FMTFLAG指定两次 - 作为枚举的一部分,而另一个实例为静态const变量
- 编译器是否可以从全局变量中读取两次,而不是存储一个局部变量
- 在 for 循环(链表)中删除两次后,变量不可用
- 具有两个变量的"for"循环,一个变量每次迭代递增,每隔一次迭代递增
- 类成员的C++静态成员变量实例化了两次
- 静态成员变量初始化两次
- 为什么比较两次 char 变量比比较一次短变量更快
- C++程序要求我输入两次,即使变量第一次被分配
- 将两次使用的字符放在变量中是空间的增益
- 由于在序列点之间修改变量两次而导致的 UB 是否会转移到"inner"范围?
- 如何防止局部变量被析构两次?堆腐败
- 对初始化列表中使用了两次的变量进行递增——未定义的行为
- 为什么静态变量需要在c++中声明两次?
- 如何避免互斥变量被同一线程锁定两次
- 重新分配变量,删除调用了两次(C++)
- 复制构造函数——用相同的变量按值调用函数两次会导致问题
- 在C++中调用线程两次时,变量重叠