Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Read File with multiple column

Tags:

c++

I'd like to read a file with multiple columns, different variable types. The number of columns is uncertain, but between 2 or four. So for instance, I have a file with :

  • string int
  • string int string double
  • string int string
  • string int string double

Thanks!

I edited to correct the number of columns to between 2 or 5, not 4 or five as originally written.

like image 908
RaymondMachira Avatar asked Mar 04 '13 16:03

RaymondMachira


1 Answers

You can first read the line with std::getline

std::ifstream f("file.txt");
std::string line;
while (std::getline(f, line)) {
...
}

and then parse this line with a stringstream

std::string col1, col3;
int col2;
double col4;
std::istringstream ss(line);
ss >> col1 >> col2;
if (ss >> col3) {
    // process column 3
    if (ss >> col4) {
        // process column 4
    }
}

If the columns might contain different types, you must first read into a string and then try to determine the proper type.

like image 106
Olaf Dietsche Avatar answered Nov 16 '22 07:11

Olaf Dietsche