【发布时间】: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 文件,但它是一个分隔文件,因此同样的方法也适用。您只需在适当的地方将
,更改为|。