gpt4 book ai didi

c++ - 如果我输入一个字母,为什么这段代码会陷入无限循环?

转载 作者:行者123 更新时间:2023-11-28 05:45:10 25 4
gpt4 key购买 nike

int readUntilValidBaseRead( int &base )
{
base = 0;
while ( base > 9 || base < 2)
{
cout << "Enter Base: " << endl;
cin >> base;
if (base > 1 && base < 10)
{
return base;
}
else
{
cout << "a valid base number is in the range of 2 to 9 inclusively" << endl;
base = 0;
}
}

对于我正在做的作业,我需要使用一个函数来获取一个基数,这就是我写的。如果输入任何数字,代码工作正常。如果我输入 f,则代码会重复执行

a valid base number is in the range of 2 to 9 inclusively 
Enter Base:

最佳答案

您需要检查此语句的结果或状态:

cin >> base;

如果输入不是数字,它将失败。输入失败时base的值未定义。

试试这个:

if (cin >> base)
{
// User input a valid number
}

关于c++ - 如果我输入一个字母,为什么这段代码会陷入无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36365074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com