如何改变for循环,使我可以使用eof
How change a for loop so I can use eof?
所以我必须创建一个代码,我从两个文件,库存和订单读取。我已经比较了订单,得到了完成的项目数量和总金额。下面的程序满足了所有需要,但是,我必须使用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,但是下一次迭代会失败。)
相关文章:
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- 访问我以前可以访问的功能时出现分段错误
- 我是否可以使用 win32 句柄以编程方式记录发送到/接收到 USB/COM 的内容
- 我想知道我是否可以将一个类分配给特定的成员数据并创建该类的实例
- 即使在超出范围之后,我是否可以保留矢量数据
- 我有点问题,我似乎可以理解这个错误
- 我真的可以使用 Type 的每个声明创建一个全局变量吗?
- 给定这两种类型,我是否可以确定虚拟函数是否已被覆盖?
- 我是否可以拥有大小大于大小限制 (2^32) 的特征::VectorXd
- 我应该把Boost.Python的.so文件放在哪里,这样我就可以把它作为一个模块导入,以及我如何将它与Python 2
- 我是否可以使用 openCV C++从带有红外滤光片的相机捕获的图像中计算 NDVI
- 我是否可以像访问自己的对象一样访问对象的'base part'?
- 我是否可以将外部库(OPENCV,MLPACK)编译到MCU上
- 有人可以帮助我做一个时循环,以便在每次计算后我都可以继续使用CIN值
- 除了使用表达式之外,我是否可以C++访问对象
- 只要我不使用它,我是否可以安全地创建对可能无效内存的引用?
- 我是否可以阻止throw调用malloc
- 我通常可以/始终使用std ::前进而不是std ::移动
- 我是否可以保证SizeOf(type)== sizeof(无符号类型)
- 语法错误,也想知道我是否可以使这段代码更有效率