循环跳过线

时间:2016-11-23 09:10:26

标签: c++ while-loop cin

我目前有这个功能:

double GrabNumber() {
    double x;
    cin >> x;
    while (cin.fail()) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "You can only type numbers!\nEnter the number: ";
        cin >> x;
    }
    return x;
}

其目的是检查x是否为有效号码,如果有效则返回;如果不是,则返回cin >> x

在此功能期间调用它:

void addition() {
    cout << "\nEnter the first number: ";
    double a = GrabNumber();
    cout << "Enter the second number: ";
    double b = GrabNumber();
// rest of code

当我输入例如&#34; 6 +&#34;当它告诉我输入第一个数字时,它会接受它,但会立即转到第二行并将其称为错误,我甚至没有输入我的输入。

我认为这是因为第一个输入只接受&#34; 6&#34;而&#34; +&#34;转到第二个输入返回错误。因此,while

的参数必定存在问题

2 个答案:

答案 0 :(得分:4)

如果您的输入立即成功,则不要忽略该行的其余部分,这将结束到下一个输入。这可以通过简单地复制cin.ignore电话来解决。

double GrabNumber() {
    double x;
    cin >> x;

    cin.ignore(numeric_limits<streamsize>::max(), '\n'); // <--

    while (cin.fail()) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "You can only type numbers!\nEnter the number: ";
        cin >> x;
    }
    return x;
}

我将此代码作为练习留下来干掉;)

答案 1 :(得分:2)

要避免此类问题,请使用getlinestod

double GrabNumber() {
    double x;
    bool ok = false;
    do
    {
        std::string raw;
        std::getline (std::cin, raw);
        try
        {
            x = stod(raw);
            ok = true;
        }
        catch(...)
        {}
    } while(!ok);
    return x;
}

一般情况下,使用getline获取原始字符串更容易,并在之后解析它。通过这种方式,您可以检查所需的一切:字符数,符号位置,是否只有数字字符,等。