I am writing a program that reads a comma-delimited file. There are several words on each line that will each be assigned to a string variable, each line in the file is a record, and the file contains several records.
I am using getline with a delimiter,
e.g. getline(inputstream, string, delimiter)

The problem I am having is that this command reads through the newline, up until the next comma (my delimiter), so that where I should have two strings, I get one long string.

My code:

      getline(input, token, ',')
       //Do some stuff to the token string here


For instance if the file contains


My getline command creates the following strings:
Bob, Saget, PimpCarrot, Top, Comedian.

So essentially, how do I use the comma and the newline character as delimiters for the same read function?

10 Years
Discussion Span
Last Post by John A

Something like this.
Do not use eof for end-of-file checking.

ifstream    file(filename);
string      line;
if (file)
    string token;
    stringstream iss;
    while ( getline(file, line) )
        iss << line;
        while ( getline(iss, token, ',') )
            cout << token << endl;

I would use getline() without the deliminator to that it will read the entire line up to the CR/LF into a string, then parse the string for commas.

[edit] Yup, same as what WolfPack posted [/edit]


Sorry for ressurrecting this thread, but Can you guys explain why Wolf's solution works? Like, explain what's going on?


>Can you guys explain why Wolf's solution works?
The first getline() works like it's usually used: it grabs an entire line, so in other words, uses the newline as a delimiter.

Then for each line that getline() grabs, it's popped into a stringstream (so that getline can use it again), and then getline() is used with a custom delimeter, the comma, to split up each line.

Hope that made sense.

This article has been dead for over six months. Start a new discussion instead.
Be sure to adhere to our posting rules.