gpt4 book ai didi

c++ - 使用 getline fstream 读取文件

转载 作者:太空宇宙 更新时间:2023-11-04 11:34:33 25 4
gpt4 key购买 nike

我对 getline 有点问题。我想逐行阅读,但只有 >> 阅读有效,而 getline 没有阅读。这是我的代码:

int studentSize;
string programme;
filein >> studentSize;
filein >> programme;
if (programme == "Physics")
{
for(int i=0; i < studentSize; i++)
{
getline (filein,namephys, '*');
filein >> idphys;
getline (filein,course, '*');
filein >> mark;

phys.push_back(new physics());
phys[i]->setNameId(namephys, idphys);
phys[i]->addCourse(course, mark);
sRecord[idphys] = phys[i];
}
}

这是我的文件:

2
Physics
Mark Dale*
7961050
Quantum Programming*
99

Mark Dale 和 Quantum Programming 的输出效果不佳。似乎整条线都摆在他们面前。感谢您的帮助。

最佳答案

流可能随时失败,您的循环无法对其作出 react 。你应该这样做:

if( programme == "Physics" )
{
filein.ignore();

// a more strict version is : (#include <limits>)
//filein.ignore( numeric_limits<streamsize>::max(), '\n' );

while( getline(filein, namephys, '*') &&
filein >> idphys &&
filein.ignore() && //** ignore the trailing newline (operator>> doesn't read it)
getline(filein, course, '*') &&
filein >> mark &&
filein.ignore() )
{
/* do something */
}
}

只要流状态变坏,这个循环就会立即退出

关于c++ - 使用 getline fstream 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23354646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com