Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use getline to delimit by comma *and* <space> in c++?

Tags:

c++

chicken, for sale, 60

microwave, wanted, 201.

These are examples lines from my txt file. Right now this is my code:

while(getline(data, word, '\n')){
    ss<<word;

    while(getline(ss, word, ',')){//prints entire file
        cout<<word<<endl;
    }
}

and my output is:

chicken
 for sale
 60

My file is succesfully parsed line by line, but I also need to get rid of that space after each comma. Adding a space after the comma here just gives me an error "no matching function to call 'getline(...:

 while(getline(ss, word, ', '))

SOLUTION: I just used the erase function

 if(word[0]==' '){//eliminates space
        word.erase(0,1);
    }

1 Answers

You could use std::ws to get rid of any leading whitespace of each part:

while(getline(ss >> std::ws, word, ','))
like image 186
O'Neil Avatar answered Sep 04 '25 00:09

O'Neil