C ++如何使用分隔符读取一行直到每行结束?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40303500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:22:08  来源:igfitidea点击:

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

c++getline

提问by weeo

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 1 type to many...I wonder how could I read those until the end of each line?

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

I'm currently 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 doesn't stop at the end of each line...How could I fix this?

所以它不会停在每一行的末尾......我怎么能解决这个问题?

回答by Sam Varshavchik

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

尝试一次解析这个输入文件一个字段是错误的方法。

This is a text file. A text file consists of lines terminated by newline characters. getline()by itself, is what you use to read a text file, with newline-terminated lines:

这是一个文本文件。文本文件由以换行符终止的行组成。getline()就其本身而言,它是您用来读取带有换行符终止行的文本文件的内容:

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

And not:

并不是:

while(!myfile.eof())

which is always a bug.

这总是一个错误

So now you have a loop that reads each line of text. A std::istringstreamcan be constructed inside the loop, containing the line just read:

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

   std::istringstream iline(line);

and then you can use std::getline(), with this std::istringstreamwith the optional delimiter character overriden to '|'to read each field in the line.

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