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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With