如何在将某个值输入到变量中后摆脱 while 循环

How to bail out of a while loop once a certain value is inputted into a variable

本文关键字:变量 循环 while 输入      更新时间:2023-10-16

我正在制作一个在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 值,并留下它们的整数值。还有其他方法可以做到这一点,但这是一种常用的方法。