循环永远不会开始



我正在编写一个简单的函数,该函数应该将用户的输入作为字符串读取。检查字符串是否仅由数字组成,然后将其转换为和int并返回。问题是无论输入如何,都不会使用循环。我正在努力寻找问题的根源。

int correctInt()
{
string temp;
int input;
bool m;
do
{
m = false;
getline(cin, temp);
int length=temp.length();
for (int a = 0; a < length; a++)
{
if (temp[a] < '0' && temp[a]>'9')
{
cout << "ID should consist of numbers. Try again: ";
m = true;
break;
}
}
if (!m)
{
return input = atoi(temp.c_str());
}
} while (1);
}

提前感谢

您应该使用OR而不是AND:

temp[a] < '0' || temp[a]>'9'

尝试更改&amp;(和(条件到||(或(条件

if (temp[a] < '0' || temp[a]>'9')

最新更新