我要做的是将数据输入到数组中,该数组最多可容纳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;
}
答案 0 :(得分:2)
尝试像这样控制你的循环:
for(int i = 0; i < SIZE; i++)
{
inp_1 >> tripNumber[i] >> fuel >> waste >> misc;
if (!inp_1)
break;
// etc...
}
您应该在输入命令之后立即检查文件状态,如上所述。 for循环确保数组不会溢出。
答案 1 :(得分:0)
尝试
for(int i = 0; i < 200 && !inp_1.eof(); i++)
{
// .....
}
答案 2 :(得分:0)
您不检查文件中的记录数是否大于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 << "\t\t"
<< final << std::endl;
finalTrip[i] = final;
++i;
}