C++ 循环不起作用,程序在第一次迭代和第二次迭代之间终止

C++ 循环不起作用,程序在第一次迭代和第二次迭代之间终止,c++,C++,这是相关代码。整个项目没有问题 list<Line> loadText(const string &textFile) { ifstream txt; string temp; char ch; list<Line> fullText; unsigned length; txt.open(textFile.c_str()); if (!txt) { cout << "Can't ope

这是相关代码。整个项目没有问题

list<Line> loadText(const string &textFile)
{
   ifstream txt; 
   string temp;
   char ch;
   list<Line> fullText;
   unsigned length;

   txt.open(textFile.c_str());
   if (!txt) 
   {
       cout << "Can't open " << txtFile << " \n";
       exit(1);
   }

   // process file line by line
   txt.seekg (0, ios::end);
   length = txt.tellg();
   txt.seekg (0, ios::beg);
   cout << length;
   for(int j = 0; j < length; j++)
   {
       cout << j;
       txt.get(ch);
       temp += ch;
       cout << ch;
       if (ch == '\n')
       {
          cout << temp;
          Line line(temp);
          row.printLine();
          fullText.push_back(row);
          cout<< "line done \n";
       }
   }
我得到如下输出:

Line 1
Line 2
Line 3
Line 4
loading maze...
 30 0L1i2n3e4 516
 Line 1
 Line 1
 line done
destroyed
请注意,destroyed只是调用Lines析构函数时给出的输出


很明显,在第一次迭代之后它就有问题了,但是经过几个小时的努力,我还没有弄明白这一点。

代码的整个读取部分可以通过以下方式简化:

while ( getline( txt, temp ) )
{
    cout << temp;
    Line line(temp);
    //row.printLine(); what is this?
    line.printLine(); // ???
    fullText.push_back(line); //???
    cout<< "line done \n";
}

您可以使用以下命令获取所有行:

while(!txt.eof()){
    char buffer [256] ;
    txt.getline(buffer , sizeof(buffer) ) ; // default delimiter : '\n'
    if(!txt.fail()){
        //todo
    }
}

已发布的功能不完整。它缺少return语句和closing}。请使用getline逐行读取。读取完每一行后,应清除temp变量。此外,在Windows上,换行符前面有一个回车符,这意味着插入指针将移动到控制台中行的开头,这可以在打印输出中产生有趣的内容。最好使用getline,然后将字符串与std::endl连接起来,而不是以“\n”结尾。-1:谢谢。这将大大清理代码。我觉得一开始不使用getline有点像个傻瓜。然而,这并不能解决我的问题。现在它输出:行1行1行完成销毁。也许是我的析构函数出了问题~行{delete&lineChars;别担心,问题出在我的析构函数上。但出于某种原因,它不允许我编辑我的评论。