【问题标题】:Loop wont work, program terminates between first iteration and second循环不起作用,程序在第一次迭代和第二次迭代之间终止
【发布时间】:2014-05-02 06:31:57
【问题描述】:

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

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

所以这个函数是用来获取一个文本文件,并创建一个行列表(一个存储字符列表的自定义类)。所有的“cout”都用于调试目的。

如果我输入这样的文本文件:

Line 1
Line 2
Line 3
Line 4

我得到这样的输出:

loading maze...
 30 0L1i2n3e4 516
 Line 1
 Line 1
 line done
destroyed

请注意,destroyed 只是在调用 Lines 析构函数时给出的输出。

所以很明显它在第一次迭代之后就出现了问题,但是经过几个小时的尝试解决这个问题,我还没有弄清楚。

【问题讨论】:

  • 贴出的功能不完整。它缺少return 语句以及结束}
  • 使用getline逐行读取。
  • 读完每一行后,清除temp变量。
  • 另外,在 Windows 上,在换行符之前有一个回车符,这意味着“插入指针”移动到控制台中的行首,这可能会导致有趣的打印输出中的东西。最好使用getline(),然后用std::endl 连接字符串,而不是用'\n' 结束它们。

标签: c++


【解决方案1】:

整个读取部分的代码可以简化如下:

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

【讨论】:

  • 谢谢。这清理了很多代码。我觉得一开始不使用 getline 有点笨。但是它不能解决我的问题。现在它输出:第 1 行第 1 行完成销毁。也许这是我的析构函数的问题? ~Line(){ 删除 &lineChars; cout
  • 别担心,问题出在我的析构函数上。出于某种原因,它不会让我编辑我的评论。
【解决方案2】:

您可以使用以下方式获取所有行:

while(!txt.eof()){
    char buffer [256] ;
    txt.getline(buffer , sizeof(buffer) ) ; // default delimiter : '\n'
    if(!txt.fail()){
        //todo
    }
}
猜你喜欢
  • 2020-06-13
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
  • 2010-12-28
  • 1970-01-01
  • 2015-10-20
  • 2012-03-05
  • 1970-01-01
相关资源
最近更新 更多