我正在尝试将两个文本文件读取到单独的数组中,但是当我调试时,从文件中读取的数字会变成垃圾。我认为这是我放置数组的方式,但我不完全确定,或者可能是因为循环中的计数器和数组中的 i 很奇怪?
void read(ifstream &A_bank, ifstream &B_bank, string &n1, string& n2, int &i,
int& j, float &num, float &num1, float &total, float &total1,
float a[], float b[])
{
int counter = 0, counter1 = 0 ;
getline(A_bank,n1);
for(int i = 0; !A_bank.eof();i++)
{
A_bank >> a[i];
total+=a[i];
counter++;
}
getline(B_bank,n2);
for(int j = 0; !B_bank.eof();j++)
{
B_bank>>b[j];
total+=b[j];
counter1++;
}
}
最佳答案
您的问题之一是错误地使用了 eof()
函数。
请参阅:http://en.cppreference.com/w/cpp/io/basic_ios/eof
eof() 仅在最后一次读取操作失败时返回 true - 而不是当最后一次读取操作是最后一次可能的读取操作时。
像这样改变你的两个循环:
for(int j = 0; /*somehow test j here: j < MAX...*/;j++)
{
int br;
if (!(B_bank>>br)) {
break;
}
b[j] = br;
total+=b[j];
counter1++;
}
关于c++ - 我正在尝试使用函数将文本文件读入 C++ 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13368539/