简体   繁体   English

Fstream从文件读取并循环C ++

[英]Fstream reading from file and looping C++

Hello I have a question about looping and reading files using fstream . 您好,我有一个关于使用fstream循环和读取文件的问题。 I have this code and the problem is I can't get it to loop. 我有这段代码,问题是我无法使其循环。

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];
        }
    }
}

I tried to add a while loop before the code. 我试图在代码之前添加一个while循环。 And do something like this: 并执行以下操作:

filein >> studentSize;
filein >> programme;
filein >> repeat;
filein.ignore();
while(repeat == '&')
  { //above code }

and make my file like this so that it loops when fstream >> detects the & character but it doesn't work. 并使我的文件像这样,以便在fstream >>检测到&字符时循环播放&但它不起作用。 I have no idea why. 我不知道为什么。

2
Mathematics
&
Ashley    
7961000
Doto
99
C++
99
Meh
99
&
Dwayne
7961222
Quantum
99
heh*
99
Computing
99

Using ignore() is a poor way to consume a & . 使用ignore()是消耗&的不良方法。 This is a working parse of your sample input: 这是示例输入的有效解析:

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 &
}

Live Demo 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM