Fstream从文件中读取并循环C++
Fstream reading from file and looping C++
你好,我有一个关于使用
fstream
循环和读取文件的问题。我有这个代码,问题是我无法使它循环。
int studentSize, mark1,mark2,mark3;
string programme, course1, course2, course3;
filein >> studentSize;
filein >> programme;
filein.ignore();
while(getline(filein, name, 'n') &&
filein >> id &&
filein >> ws &&
getline(filein, course1, 'n') &&
filein >> mark1 &&
filein >> ws &&
getline(filein, course2, 'n') &&
filein >> mark2 &&
filein >> ws &&
getline(filein, course3, 'n') &&
filein >> mark3 &&
filein >> ws)
{
if( programme == "Physics" )
{
for(int i=0; i < studentSize; i++)
{
phys.push_back(new physics());
phys[i]->setNameId(name, id);
phys[i]->addCourse(course1, mark1);
phys[i]->addCourse(course2, mark2);
phys[i]->addCourse(course3, mark3);
sRecord[id] = phys[i];
}
}
}
我试图在代码之前添加一个while循环。做这样的事情:
filein >> studentSize;
filein >> programme;
filein >> repeat;
filein.ignore();
while(repeat == '&')
{ //above code }
并使我的文件像这样,以便在fstream >>
检测到&
字符但不起作用时循环。我不知道为什么。
2
Mathematics
&
Ashley
7961000
Doto
99
C++
99
Meh
99
&
Dwayne
7961222
Quantum
99
heh*
99
Computing
99
使用ignore()
是消耗&
的一种糟糕方法。这是您的示例输入的工作解析:
int studentSize, id, mark1,mark2,mark3;
string name, programme, course1, course2, course3;
char delim;
cin >> studentSize >> programme >> delim;
cout << studentSize << ", " << programme << ", " << delim << endl;
while(cin >> name >> id >> course1 >> mark1 >> course2 >> mark2 >> course3 >> mark3)
{
//do more stuff with your variables here
cout << name << ", " << id << ", " << mark1 << ", " << course1 << ", " << mark2 << ", " << course2 << ", " << mark3 << ", " << course3 << < endl;
cin >> ws >> delim; //consume the &
}
实时演示
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在基于范围的for循环中使用结构化绑定声明
- 用于C++中带有数组和指针的循环
- 循环中的随机函数
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 在循环C++中指定字符串之后,不会打印该字符串