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?

Recommended Answers

All 6 Replies

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]

Nested getlines, that's a good idea. Thanks a lot.

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.

int main ()
    std::string name;
    string last;

    std::cout << "Please, enter your full name: ";
    std::getline (std::cin,name,',');
    std::getline (std::cin,last,',');
    std::cout << "Hello, " << name << "!\n";
    std::cout << "Hello, " << last << "!\n";

    return 0;

Basically, you only need to use getline() manytimes and you gonna get results below.

Please, enter your full name: Tom,qqww,eess,e
Hello, Tom!
Hello, qqww!
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.