簡體   English   中英

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

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM