如何在将某个值输入到变量中后摆脱 while 循环
How to bail out of a while loop once a certain value is inputted into a variable
我正在制作一个在C++中使用while循环的程序。这是我到目前为止的代码:
int userInput = 0;
while (userInput != 'Z')
{
cout << "Please enter the homework score: ";
cin >> userInput;
homeworkScores.push_back(userInput);
if (userInput == 'Z') {
userInput = 'Z';
}
}
我遇到的问题是每当我键入 Z 时,循环都会一遍又一遍地打印"请输入家庭作业分数:"而不停。我在代码前面将 homeworkScore 定义为一个向量。如何让它在用户输入 == 'Z' 后停止循环?提前感谢!
您面临的问题是cin
正在尝试读取整数,但您在输入中提供了一个字符。cin
只会要求另一个输入,一旦输入为空,您可以通过向代码提供多个整数来尝试此操作:
Please enter the homework score: 2 27 12 8
将输入所有四个数字并打印"请输入家庭作业分数:"4次。
如果您为其提供字符,它不会将其从输入中删除,因此每当到达"cin"时,它将在输入中看到"Z",并继续。
您可以使用此处提供的答案 如何在 c++ 中捕获无效输入? 用于您的输入卫生,但它不会使"Z"作为停止。
最简单的方法是选择一个无效的分数,如 -1 而不是 Z,在任何无效输入上结束,或者在读取 int 失败时尝试读取字符串。
退出循环的一种简单方法是使用break
语句。
if (userInput == 'Z') {
userInput = 'Z';
break;
}
其他方法是将您的退出条件设置为false
解决,我认为这会给您带来一些问题。
编辑:正如@Ganea Dan Andrei所指出的那样,将字符从cin
读取为整数将导致cin::fail()
返回true
。这可以通过调用cin.clear()
来重置,这将允许您进行进一步的输入。
userInput
是一个整数,因此"Z"必须等于其char
值的ASCII等效值,即90
。你这样做的方式不应该奏效。相反,请尝试将userInput
设为char
,然后将其转换为整数,以便将其推回向量。这可能如下所示:
char userInput = '';
while (userInput != 'Z')
{
cout << "Please enter the homework score: ";
cin >> userInput;
homeworkScores.push_back(userInput - '0'); //Are you sure you want to push a 'Z'?
if (userInput == 'Z') {
userInput = 'Z';
break;
}
userInput = ''; // Reset your input so it doesn't keep getting pushed new values
}
这里发生的情况是userInput - '0'
减去字符的 ASCII 值,并留下它们的整数值。还有其他方法可以做到这一点,但这是一种常用的方法。
- 在循环中按顺序遍历成员变量
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 与 for 循环中的变量混淆
- 如何在循环之外重新输入变量
- 如何使用将字符串拆分为 for 循环中的变量的程序
- 在变量声明中使用 for 循环
- C++ 和 Boost.Python - 如何将变量公开给 python 并在循环中更新它?
- C++ Code 在 for 循环期间不会累积变量中的总和,仅提供最终迭代值
- C++ 在循环中添加计数器变量并再次初始化其值
- (C++)虽然循环一次不起作用,但我引入了多个变量
- 如何添加循环期间分配的变量?
- C++,每个循环初始化一个新的静态变量
- 在 for 循环中更新两个变量时遇到问题C++
- 循环中的变量被设置为下一个数组的元素始终具有相同的内存地址?
- 需要循环帮助以迭代方式添加到程序集中的总和变量
- 在 c++ 中基于范围的 for 循环中使用引用作为控制变量
- 如何在循环中动态创建变量(c++)
- 变量循环范围会导致返回局部变量的地址引用
- ifstream变量循环不打印任何内容
- c++变量/循环问题