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.