【问题标题】:While loop skips lineWhile循环跳过行
【发布时间】:2017-04-07 04:56:45
【问题描述】:

我目前有这个功能:

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 &gt;&gt; x

在这个函数中被调用:

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

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

我认为这是因为第一个输入只接受“6”,而“+”转到第二个输入返回错误。所以while的参数肯定有问题。

【问题讨论】:

  • 我认为你将不得不使用getline 并解析完整的行,而不是像那样使用cin
  • 但 Getline 读取为字符串

标签: c++ while-loop cin


【解决方案1】:

如果您的输入立即成功,您不会忽略该行的其余部分,它会进入下一个输入。只需复制 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;
}

我会把 DRY 这段代码作为练习 ;)

【讨论】:

    【解决方案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 获取原始字符串并在之后解析它更容易。通过这种方式,您可以检查您想要的所有内容:字符数,符号位置,是否只有数字字符,等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 2013-04-23
      • 1970-01-01
      相关资源
      最近更新 更多