c++如何用分隔符读取一行,直到每行结束

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

本文关键字:一行 结束 c++ 分隔符 何用 读取      更新时间:2023-10-16

你好,我需要读取一个文件,看起来像这样…

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

正如你所看到的,每部电影的类型可以从一种类型到多种类型…我想知道我怎么才能读到每一行的末尾呢?

我正在做:

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;
    }
}
结果不是我想要的…它看起来像:
Animation
Children's
Comedy
2
Jumanji (1995)
Adventure
Children's
Fantasy
3
Grumpier Old Men (1995)
Comedy
Romance

所以它不会在每行结束时停止…我怎样才能解决这个问题?

试图一次解析一个字段是错误的方法。

是一个文本文件。文本文件由以换行符结束的行组成。getline()本身是用来读取文本文件的,具有以换行符结束的行:

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

而不是:

while(!myfile.eof())

总是一个bug。

现在你有一个循环,读取每一行文本。std::istringstream可以在循环内构造,包含刚刚读到的行:

   std::istringstream iline(line);

,然后您可以使用std::getline(),这个std::istringstream与可选的分隔符字符覆盖到'|'来读取行中的每个字段。