gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:50:15 26 4
gpt4 key购买 nike

我想做的是将数据输入一个数组,该数组最多可以容纳 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com