C ++ Reading a file with multiple columns

I would like to read a file with several columns, different types of variables. The number of columns is undefined, but from 2 to 4. So, for example, I have a file with:

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

Thanks!

I edited to fix the number of columns in the range of 2 to 5, rather than 4 or five, as was originally written.

+4
source share
1 answer

You can read the line with std::getline

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

and then stringstream this string with 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 can contain different types, you must first read the row and then try to determine the correct type.

+5
source

All Articles