如何改变for循环,使我可以使用eof

How change a for loop so I can use eof?

本文关键字:我可以 可以使 eof 循环 for 何改变 改变      更新时间:2023-10-16

所以我必须创建一个代码,我从两个文件,库存和订单读取。我已经比较了订单,得到了完成的项目数量和总金额。下面的程序满足了所有需要,但是,我必须使用eof(),我不知道如何使用。这部分程序之前的行只是简单地读取文件,并将文件的信息导入到文件的内部名称instam1和instam2中。提前谢谢你。

for(int i=0;i<ord;i++){ 
    for(int j=0;j<inv;j++){ 
        if(prod_ord[i] == prod_code[j])       
            {
            if(order[i] <= units[j])
            {
                fullfill[i]= order[i];
                amt_billed[i] = fullfill[i] * unitprice[j];
            }
            else
            {
                fullfill[i]= units[j];
                amt_billed[i] = fullfill[i] * unitprice[j];
            }               
            }
        else
            {
                cout<< "Order invalid."<<endl;
    }
    }

}

float total_due = 0;
cout<< "Order#: order0923nSalesman: full namen t Fullfilled t Amt Billed" <<endl;
    for(int i= 0;i<ord;i++)
    {
        cout<< prod_ord[i]<<" t"<<fullfill[i]<<" t"<<amt_billed[i]<<endl;
        total_due += amt_billed[i];  
    }
cout<<"Total Due: $"<<total_due<<endl;

如果您使用的是eof(),您可能是指使用它来确定何时停止读取输入。也就是说,你想要终止条件,for循环的第二个子句,调用eof()。这不是一个完整的解决方案,因为这看起来像作业,但基本上有两种等效的方法:

for (records = 0; !std::cin.eof(); ++records) {
  // Parse a record and store it, preferably in a vector.
  // The records variable stores the number of records.
}

:

int records = 0;
while (!std::cin.eof()) {
  // Read in and store a record, preferably in a vector.
  ++records;
}

但要注意

注意,如果在读取记录时输入包含EOF ,那么这两种方法都将失败。所以你想要的是(未测试):

bool read_record( std::istream&, record_t& );
using std::cin;
constexpr size_t SOME_REASONABLE_NUMBER = 4096U/sizeof(record_t);
std::vector<record_t> recordv;
recordv.reserve(SOME_REASONABLE_NUMBER);
while (cin.good()) {
  record_t this_record;
  if (read_record(cin, this_record))
    recordv.push_back(this_record);
  else
    break;
}

如果您使用内置类型或重载std::istream::operator>>, record_t this_record; while (cin >> this_record)将工作。(它返回对cin的引用,如果流上没有错误,则计算结果为true。它不检查EOF,但是下一次迭代会失败。)

相关文章: