C ++ how to read a line with a separator to the end of each line?

Hi, I need to read a file that looks like this:

1|Toy Story (1995)|Animation|Children's|Comedy
2|Jumanji (1995)|Adventure|Children's|Fantasy
3|Grumpier Old Men (1995)|Comedy|Romance
4|Waiting to Exhale (1995)|Comedy|Drama
5|Father of the Bride Part II (1995)|Comedy
6|Heat (1995)|Action|Crime|Thriller
7|Sabrina (1995)|Comedy|Romance
8|Tom and Huck (1995)|Adventure|Children's
9|Sudden Death (1995)|Action

As you can see, the type of each movie can vary from one type to many ... I wonder how I could read them to the end of each line?

Now I am doing:

void readingenre(string filename,int **g)
{

    ifstream myfile(filename);
    cout << "reading file "+filename << endl;
    if(myfile.is_open())
    {
        string item;
        string name;
        string type;
        while(!myfile.eof())
        {
            getline(myfile,item,'|');
            //cout <<item<< "\t";
            getline(myfile,name,'|');
            while(getline(myfile,type,'|'))
            {
                cout<<type<<endl;
            }
            getline(myfile,type,'\n');
        }
        myfile.close();
        cout << "reading genre file finished" <<endl;
    }
}

the result is not what I want ... It looks like:

Animation
Children's
Comedy
2
Jumanji (1995)
Adventure
Children's
Fantasy
3
Grumpier Old Men (1995)
Comedy
Romance

So it does not stop at the end of each line ... How can I fix this?

+4
source share
2 answers

Thanks guys ... I used istringstream. He works.

getline(myfile,type);
istringstream ss(type);
string temp;
while(getline(ss,temp,'|'))
{
     cout<<temp<<endl;
}
0
source

Trying to parse this input file one field at a time is the wrong approach.

. , . getline() , , , :

while (std::getline(myfile, line))

:

while(!myfile.eof())

.

, , . A std::istringstream , :

   std::istringstream iline(line);

std::getline(), std::istringstream - '|', .

+2

Source: https://habr.com/ru/post/1659176/


All Articles