【问题标题】:Accepting a Blank Value for istream接受 istream 的空白值
【发布时间】:2017-08-08 01:23:11
【问题描述】:

我编写了这段代码,旨在使用产品的参数 istr 接收值,并且运行良好,但我意识到您不能只将字段留空。我的一个字段处理产品的单位,而某些产品没有单位,在这种情况下,用户只需按 Enter 键即可继续下一个收到的值,但问题是它只是不断换行,直到正确值被接收。我还能做些什么来接受空白值?我只关注单位字段,但如果有人需要,我提供了整个功能。这是我的代码:

std::istream& AmaProduct::read(std::istream& istr) { //receives values using istr argument
    char skuField[10];
    char nameField[100];
    double priceField;
    char taxField;
    int qtyField;
    char unitField[11];
    int qtyNeededField;
    if (!istr.fail()) {
      err_.clear();
    }
    cout << "Sku: ";
    istr >> skuField;
    sku(skuField);
    cout << "Name: ";
    istr >> nameField;
    name(nameField);
    cout << "Unit: ";
    istr >> unitField;
    unit(unitField);
    err_.clear();
    cout << "Taxed? (y/n): ";
    istr >> taxField;
    if (taxField == 'Y' || taxField == 'y' || taxField == 'N' || taxField == 'n') {
      taxed(taxField == 'Y' || taxField == 'y');
      istr.ignore(500, '\n');
    }
    else {
      err_.message("Only (Y)es or (N)o are acceptable");
      istr.setstate(ios::failbit);
    }
    if (err_.isClear()) {
    cout << "Price: ";
    istr >> priceField;
    price(priceField);
    }
    if (istr.fail() && err_.isClear()) {
      err_.message("Invalid Price Entry");
    }
    if (err_.isClear()) {
    cout << "Quantity On hand: ";
    istr >> qtyField;
    quantity(qtyField);
    }
    if (istr.fail() && err_.isClear()) {
      err_.message("Invalid Quantity Entry");
    }
    if (err_.isClear()) {
    cout << "Quantity Needed: ";
    istr >> qtyNeededField;
    qtyNeeded(qtyNeededField);
    }
    if (istr.fail() && err_.isClear()) {
      err_.message("Invalid Quantity Needed Entry");
    }
  return istr;
  }
}

【问题讨论】:

    标签: c++ istream


    【解决方案1】:

    通过std::getline() 读取值。如果你得到一个非空字符串,解析它,否则跳过它。

    【讨论】:

    猜你喜欢
    • 2018-04-03
    • 2018-01-26
    • 2015-01-13
    • 2021-12-29
    • 1970-01-01
    • 2012-02-28
    • 2014-04-17
    • 2023-03-16
    • 2014-02-24
    相关资源
    最近更新 更多