【问题标题】:A loop never starts循环永远不会开始
【发布时间】:2020-04-30 11:25:49
【问题描述】:

我正在编写一个简单的函数,它应该将用户的输入作为字符串读取。检查字符串是否仅由数字组成,然后将其转换为 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);
}

提前谢谢你

【问题讨论】:

标签: c++ loops for-loop


【解决方案1】:

你应该使用 OR 而不是 AND:

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

【讨论】:

  • 谢谢,这更有意义。现在想想
【解决方案2】:

尝试将 && (and) 条件更改为 || (或)条件

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-20
    • 2012-09-14
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多