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

c++ Stopping for loop once reaching array size or eof

本文关键字:eof 循环 数组 c++      更新时间:2023-10-16

我要做的是将数据输入到一个数组中,数组最多可以容纳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 << "tt" << final << endl;
        finalTrip[i] = final;
    }

cout << "Totals" << "t" << totalFuel << "t" << totalWaste << "t " << totalMisc << "t " << totalDiscount << "tt" << 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循环确保数组不会溢出。

尝试

for(int i = 0; i < 200 && !inp_1.eof(); i++)
{
    // .....
}

您不检查文件中的记录数是否大于SIZE。

此外,还不清楚您为什么将变量定义为全局变量。至少燃料、废物和杂项可能是回路的局部变量。

在我看来,写会更正确

std::ifstream inp_1( "TripInput.txt" );
int i = 0;
std::string record;
while ( i < SIZE && std::getline( inp_1, record ) )
{
    if ( record.find_first_not_of( " " ) == std::string::npos ) continue;
    int fuel = 0, waste = 0, misc = 0;
    std::istringstream is( record );
    is >> tripNumber[i] >> fuel >> waste >> misc;
    discount = fuel - (fuel * .10);
    final = discount + waste + misc;
    totalFuel += fuel;
    totalWaste += waste;
    totalMisc += misc;
    totalDiscount += discount;
    totalFinal += final;
    std::cout << std::setprecision( 0 ) << tripNumber[i];
    std::cout << std::setprecision( 2 ) << std::fixed << "t " 
                                        << fuel << "t " 
                                        << waste << "t " 
                                        << misc << "t " 
                                        << discount << "tt" 
                                        << final << std::endl;
    finalTrip[i] = final;
    ++i;
}