0

My goal is to read a text file with some columns (here just two) and store the whole columns in vectors. Column 1 stored in column1, column 2 in column2 and so on.

#include <iostream>
#include <fstream>
#include <vector>


/* ======= global variables ======= */

double col1;
double col2;
std::vector<double> column1;
std::vector<double> column2;

The readingFile function checks at first if there are open file issues. Further it reads the text file while the file is not at the end.

My problem is that just the first line works fine. After pushing back the last entry in col3, it skips the first entry of column 1 so the whole data construct shifts. The data which was supposed to be stored in column 2 is stored in column 1 and so on.

double readingFile()
{
    std::ifstream infile("file.txt");                   
    if(!infile)
    {
    std::cerr << "* Can't open file! *" << std::endl;
    return 1;
    }
    else
    {
        // skipping first two lines.             
        infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');   

        while(infile >> col1 >> col2 >> col3)
        {
            column1.push_back(col1);
            column2.push_back(col2);
            column3.push_back(col3);
        }
    }
    infile.close();
    return 0;
}

Here is an example of some data:

 //There is some text before the actual numbers, 
 //like the name of the creator of the file. Thats why i'm "ignoring" the first two line out.
 1.2 3.4 4.6
 0.9 0.4 7.1
 8.8 9.2 2.6

The first line works fine. col1 holds 1.2 col2 holds 3.4 and col3 holds 4.6. But then 0.9 get skipped and col1 holds 0.4, col2 holds 7.1 and so on.

1 Answers1

0

Try using:

while (infile >> col1 >> col2)
{
    column1.push_back(col1);
    column2.push_back(col2);
}

The above is the preferred idiom to read from a file.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • This works for me just for the first line. For unexplainable reasons the first number of the first column is always skipped. So the whole data construct shifts. Data which were supposed to be in column3 are in column 4 etc. –  May 27 '18 at 14:26
  • Please edit your post with an example of the input data. The first line may have only one number. – Thomas Matthews May 27 '18 at 16:32
  • I added an small example of the data. Could it be that the first number in a line is skipped because of the **infile.ignore()** function? –  May 28 '18 at 08:48