c++ - 接受 istream 的空白值

标签 c++ istream

我已经编写了这段代码,旨在使用产品的参数 istr 接收值并且它运行良好,但我意识到你不能只将一个字段留空。我的一个字段处理产品的单位,而有些产品没有单位,在这种情况下,用户只需按 enter 键即可继续接收到的下一个值,但问题是它只是一直换行直到正确收到值(value)。我该怎么做才能接受空白值?我只关注单元字段,但如果有人需要查看,我会提供完整的功能。这是我的代码:

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;
  }
}

最佳答案

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

关于c++ - 接受 istream 的空白值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45557907/

相关文章:

c++ - MySql connector-c++ 不会在 QtCreator 中链接,但在树莓派 pi3 上本地工作正常

c++ - 在 Qt Creator 中将库链接到 CMake (MSVC)

c++ - CUDA - 中值滤波器实现没有产生预期的结果

c++ - 将 std::unique_ptr 与 std::istream 一起使用?

c++ - 如何从具有 null(0) 字符的 char 数组创建 C++ istringstream?

c++ - std::istream 的运算符类型无效?

c++ - 外部 dll 中缺少 Qt 信号

c++ - Windows - 动态加载库 C++

c++ - 处理异常 std::out_of_range C++

c++ - 将 std::istream 直接连接到 C-Array/unsigned char *