RaymondMachira
RaymondMachira

Reputation: 354

C++ Read File with multiple column

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.

Upvotes: 5

Views: 17037

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

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.

Upvotes: 5

Related Questions