c++一旦达到数组大小或eof就停止循环

标签 c++ arrays loops

我想做的是将数据输入一个数组,该数组最多可以容纳 200 个变量,或者直到它到达文件末尾。如果文件超过 200 个变量,这会起作用还是会继续添加?这是我到目前为止写的:

此外,如果不在未分配任何内容的元素中打印 0,您将如何以相反的顺序输出它?

#include<iostream>
#include<fstream>
#include<iomanip>

using namespace std;

const int SIZE = 200;
int tripNumber[SIZE];
double finalTrip[SIZE];
double fuel, waste, misc, discount, final;
double totalFuel, totalWaste, totalMisc, totalDiscount, totalFinal;


int main()
{
cout << "Welcome to NAME's Space Travel Company" << endl;
cout << "Trip No" << "\t" << "Fuel" << "\t" << "Waste" << "\t" << "Misc" << "\t"   << "Discount Fuel" << "\t" << "Final Cost" << endl;

ifstream inp_1("TripInput.txt");

    for(int i = 0; i = !inp_1.eof(); i++)
    {
        inp_1 >> tripNumber[i] >> fuel >> waste >> misc;
        discount = fuel - (fuel * .10);
        final = discount + waste + misc;

        totalFuel += fuel;
        totalWaste += waste;
        totalMisc += misc;
        totalDiscount += discount;
        totalFinal += final;

        cout << setprecision(0) << tripNumber[i];
        cout << setprecision(2) << fixed << "\t " << fuel << "\t " << waste << "\t " << misc << "\t " << discount << "\t\t" << final << endl;

        finalTrip[i] = final;
    }


cout << "Totals" << "\t" << totalFuel << "\t" << totalWaste << "\t " << totalMisc << "\t " << totalDiscount << "\t\t" << totalFinal << endl;

inp_1.close();

system("PAUSE");
return 0;

最佳答案

尝试像这样控制你的循环:

for(int i = 0; i < SIZE; i++)
{
    inp_1 >> tripNumber[i] >> fuel >> waste >> misc;
    if (!inp_1)
        break;
    // etc...
}

您应该在输入命令后立即检查文件状态,如上。 for 循环确保数组不会溢出。

关于c++一旦达到数组大小或eof就停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23230144/

相关文章:

c++ - Qt 没有匹配函数供调用

java - 使用一个类中的方法到另一个类中

Python,将数字乘以 2 直到大于 1000 的程序,有语法问题

javascript - Jquery 在循环内生成 Id

c++ - 在转换参数上使用 std::forward

C++ getline传文件或cin

ios - 解析iOS SDK : Not able to fetch Objects from Array

javascript - 使用过滤器和映射方法将数组中某些元素的首字母大写 - JavaScript

javascript - 循环访问站点上的链接并单击链接 javascript/jquery

c++ - 多个列表的高效排列算法