5

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.

4
  • 2
    So you want us to write you code? You're not paying us? So please do research and ask questions here about specific problems you encounter along the way. Commented Mar 4, 2013 at 16:45
  • 2
    How are the columns divided? If with whitespace (space or tab) then the normal input operator >> will work fine. Commented Mar 4, 2013 at 16:45
  • The number of columns is uncertain, but between 4 or five --- yet your example shows that the first row only contains 2 columns, and not a single one contains 5 columns! Commented Mar 4, 2013 at 16:47
  • 1) read a line. 2) tokenize it somehow. 3) come back if you have a real question. Commented Mar 4, 2013 at 17:40

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget #include <sstream>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.