我正在尝试使用一个函数在 c++ 中将文本文件读入数组

I'm trying to use a function to read text files into arrays in c++

本文关键字:c++ 文本 函数 文件 数组 一个      更新时间:2023-10-16

我正在尝试将两个文本文件读取到单独的数组中,但是当我调试时,从文件中读取的数字作为垃圾出现。我认为这是我放置数组的方式,但我不完全确定,或者可能是因为循环中的计数器和数组中的 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,而不是在上次读取操作是最后一个可能的读取操作时返回 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++;
}