c++一旦达到数组大小或eof,就停止循环
c++ Stopping for loop once reaching array size or eof
我要做的是将数据输入到一个数组中,数组最多可以容纳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;
}
相关文章:
- 为什么 EOF 在循环扫描期间没有终止?
- EOF循环在最终结束之前重复3次线
- 输入文件读取错误的值,eof 控制循环不会结束
- 永远不会达到 EOF(无限循环)
- 使用.eof()方法的无限循环
- C++使用cin.get来获取一个字符,但在遇到EOF时不会结束while循环
- C++循环在 EOF 之后继续运行时这样做
- 标志控制的环路EOF循环
- 在我的程序中使用EOF,然后连续循环
- 文件I/O Infinite循环C EOF
- eof() 函数不起作用 C++ 陷入无限循环
- EOF进入无限循环
- 而循环构造与 getline 函数相结合,一直持续到 EOF
- 我如何在没有获得 EOF 的情况下循环通过 ifstream::get
- fgetwc EOF 循环测试失败,但 65535 正常
- EOF返回空行或无限循环
- c++ boost asio Windows文件句柄async_read_until无限循环-没有eof.< /
- .eof()循环不工作
- 如何改变for循环,使我可以使用eof
- 为什么使用while(!input.eof())循环两次不工作