【问题标题】:Fstream reading from file and looping C++Fstream 从文件中读取并循环 C++
【发布时间】:2014-04-30 19:24:34
【问题描述】:

您好,我有一个关于使用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 &gt;&gt; 检测到&amp; 字符但它不起作用时它会循环。我不知道为什么。

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

【问题讨论】:

  • 那么,当您在 IDE 的调试器中单步执行它时会发生什么?
  • 它可以编译,但它会进入无限循环。
  • 我认为filein.ignore() 声明是造成您麻烦的原因...
  • 另外for(int i=0; i &lt; studentSize; i++) 可能是错误的
  • 您的条件是while(repeat == '&amp;')。你永远不会改变repeat。这个循环如何结束?

标签: c++ loops fstream


【解决方案1】:

使用ignore() 是消耗&amp; 的糟糕方式。这是您的示例输入的有效解析:

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

【讨论】:

  • cin &gt;&gt; namegetline(cin, name) 不同:后者可以读取带空格的名称。
猜你喜欢
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 2012-04-05
  • 2016-09-29
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
相关资源
最近更新 更多