2

Possible Duplicate:
Splitting a string in C++

I am trying to read data from file where each line has 15 fields separated by commas and spaces. The data are not of a single type. Currently what I am doing is reading data line by line, and pass each line to an istringstream and between each read I do the following:

ins.ignore(25,','); //ins is the istringstream

I however don't like my method and would like a cleaner one. What would be a better way of doing it?. Also I would only like to use stl and no external libraries. Basically what I want is to tokenize each line using the comma as the delimiter.

3

2 Answers 2

3

Just use a custom manipulator:

std::istream& comma(std::istream& in) {
    if ((in >> std::ws).get() != std::char_traits<char>::to_int_type(',')) {
        in.setstate(std::ios_base::failbit);
    }
    return in;
}
...
in >> v0 >> comma >> v1 >> comma ...
Sign up to request clarification or add additional context in comments.

Comments

0

Cleaner method (if I understand right) is just to read the comma into a dummy variable

char comma;
ins >> comma;

This will skip any whitespace and then read the comma, which you can then ignore.

3 Comments

I thought of doing that, but the thing is, some fields maybe empty. For example "12 , , hello". I suppose I can handle this case by checking if the read value is a comma, then i'll just set it to empty.
But then you have the issue that you'd have to 'unread' the character if it was not a comma. Sounds to me that you need to forget about stream IO and do some proper parsing on your line. Zamfir gave many links to answers to this question which gets asked a lot.
He can just peek() at the next character after skipping whitespace using std::ws. A trivial patsing activity like a comma separated file can well be done using streams.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.