【问题标题】:C++ how to read a line with delimiter until the end of each line? [duplicate]C ++如何读取带分隔符的行直到每行的末尾? [复制]
【发布时间】:2017-03-11 06:04:18
【问题描述】:

您好,我需要读取一个看起来像这样的文件...

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

所以它不会在每一行的末尾停止...我该如何解决这个问题?

【问题讨论】:

  • 在不指定分隔符的情况下读取流派部分(即使用默认分隔符'\n'),然后使用'|'分割结果。
  • 代码完全符合您的要求。你期待什么??
  • @Leon 谢谢!我应该使用什么函数来用'|'分割结果?
  • 我认为没有标准功能。检查这个:stackoverflow.com/questions/236129/split-a-string-in-c
  • 是的,这不是 CSV 文件,但它是一个分隔文件,因此同样的方法也适用。您只需在适当的地方将, 更改为|

标签: c++ getline


【解决方案1】:

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

这是一个文本文件。文本文件由以换行符结尾的行组成。 getline() 本身就是你用来读取文本文件的,带有换行符终止的行:

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

而不是:

while(!myfile.eof())

which is always a bug

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

   std::istringstream iline(line);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多