c++如何用分隔符读取一行,直到每行结束
C++ how to read a line with delimiter until the end of each line?
你好,我需要读取一个文件,看起来像这样…
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
与可选的分隔符字符覆盖到'|'
来读取行中的每个字段。
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 从C++dll访问C#中的一行主要参数
- 为什么在这个代码结束循环中没有得到结束
- 在C++中,我如何接受不同于同一行的用户输入
- 试图对缓存进行跨步测试,但程序并没有结束
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 如何从一行中读取特定数量的字符?(C++)
- 为什么擦除方法会影响结束方法
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 读取最后一行代码算法 - c++ 时出现问题
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 有没有办法在一行中填充矢量图
- 删除映射和分割错误中的一个过去结束元素
- 需要将一行代码从C++ Qt翻译成PyQt
- 为什么如果我添加这一行,我的程序会不断询问值
- 如何使用 SFML 在贪吃蛇游戏中定义游戏结束?
- gvim 换行应该结束当前字符串并在下一行开始一个新的字符串
- c++如何用分隔符读取一行,直到每行结束