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.

Community
  • 1
  • 1
turingcomplete
  • 2,128
  • 3
  • 16
  • 25
  • 6
    I believe this is a duplicate of: http://stackoverflow.com/questions/1894886/parsing-a-comma-delimited-stdstring and http://stackoverflow.com/questions/2619227/best-way-to-get-ints-from-a-string-with-whitespace and http://stackoverflow.com/questions/536148/c-string-parsing-python-style and http://stackoverflow.com/questions/3162108/a-better-way-to-split-a-string-into-an-array-of-strings-in-c-c-using-whitespac etc. – Zamfir Kerlukson Nov 23 '12 at 06:14
  • If you were ok with C, you can look at `strtok` – Karthik T Nov 23 '12 at 06:23
  • ... or sscanf("%as , %as , %as , %as...") – rici Nov 23 '12 at 06:27

2 Answers2

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 ...
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
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.

john
  • 85,011
  • 4
  • 57
  • 81
  • 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. – turingcomplete Nov 23 '12 at 06:41
  • 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. – john Nov 23 '12 at 06:51
  • 1
    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. – Dietmar Kühl Nov 23 '12 at 07:30