我已经编写了这段代码,旨在使用产品的参数 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/