0

I am using the following code to read a text file;

void load_triplet(const std::string filename,
                  std::vector<int> &rows,
                  std::vector<int> &cols,
                  std::vector<double> &data)
{
    int a;
    int b;
    double c;
    const unsigned int MAXBUFF = 1000000;
    rows.reserve(MAXBUFF);
    cols.reserve(MAXBUFF);
    data.reserve(MAXBUFF);

    std::ifstream file;
    file.open(filename, std::ios::in);

    if (file.is_open())
    {
        int counter = 0;
        while (!file.eof())
        {
            file >> a >> b >> c;
            rows.push_back(a);
            cols.push_back(b);
            data.push_back(c);
        }
        file.close();
    }
    else
    {
        std::cout << "Error reading triplet " << filename << "\n";
        exit(EXIT_FAILURE);
    }
}

Input has 11 rows and last line is empty (11 rows data and an empty line);

load_triplet("A.txt", rows, cols, data);
for (int i = 0; i < rows.size(); ++i)
    cout << i << " " << rows[i] << " " << cols[i] << " " << data[i] << endl;
int n = rows.size();
cout << "size of rows : " << n << endl;
cout << "rows[11] is " << rows[11] << endl;

My output from code is:

0 0 0 1
1 0 2 -3e+09
2 1 1 1
3 1 3 -2e+09
4 2 2 1
5 2 5 -0.00111111
6 3 3 1
7 3 4 -0.000833333
8 4 4 1
9 4 5 -3
10 5 5 1
11 5 5 1
size of rows : 12
rows[11] is 5

I have also find this questions about skipping empty lines, but I don't know how to combine them with this to read different type so I made a new question.

Abolfazl
  • 672
  • 4
  • 19
  • 4
    Instead of `while (!file.eof()) { file >> a >> b >> c;` use `while (file >> a >> b >> c) {` because the eof flag is only set when you try to read and you are already at the end which means `file.eof()` is false when you get to the end of the file so you can't use it as a while condition (you can test it after the while loop to determine if it exited the loop because of eof or because of something else) https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons – Jerry Jeremiah May 12 '21 at 05:07

0 Answers0