Can I use 2 or more delimiters in C++ function getline?

user6185425 picture user6185425 · Jun 22, 2016 · Viewed 29k times · Source

I would like to know how can I use 2 or more delimiters in the getline functon, that's my problem:

The program reads a text file... each line is goning to be like:

   New Your, Paris, 100
   CityA, CityB, 200

I am using getline(file, line), but I got the whole line, when I want to to get CityA, then CityB and then the number; and if I use ',' delimiter, I won't know when is the next line, so I'm trying to figure out some solution..

Though, how could I use comma and \n as a delimiter? By the way,I'm manipulating string type,not char, so strtok is not possible :/

some scratch:

string line;
ifstream file("text.txt");
if(file.is_open())
   while(!file.eof()){
     getline(file, line);
        // here I need to get each string before comma and \n
   }

Answer

WhiZTiM picture WhiZTiM · Jun 22, 2016

You can read a line using std::getline, then pass the line to a std::stringstream and read the comma separated values off it

string line;
ifstream file("text.txt");
if(file.is_open()){
   while(getline(file, line)){   // get a whole line
       std::stringstream ss(line);
        while(getline(ss, line, ',')){
             // You now have separate entites here
        }
   }