【问题标题】:Does anyone know why fstream crashes at this line?有谁知道为什么 fstream 在这条线上崩溃?
【发布时间】:2012-10-18 08:02:27
【问题描述】:

这是我第一次遇到这个问题,所以我不知道如何解决它。 编辑:没关系。看起来我的构造函数中的一个错误导致这种情况以某种方式发生


#include <iostream>
#include <fstream>
#include "graphm.h"

using namespace std;

int main() {

   ifstream infile1("data31.txt");

   for(;;){
      GraphM G;
      G.buildGraph(infile1);
      if (infile1.eof()) 
         break;
}

void GraphM::buildGraph(ifstream& infile){
    int i = 0;
    infile >> i;     //it crashes here
}

我的文本文件只有 1 行: 5

【问题讨论】:

  • 您能否为GraphMfor 循环的其余部分发布构造函数和析构函数。对G.buildGraph() 的第一次调用不会设置eof(),因此将执行循环的第二次迭代。

标签: c++ fstream ifstream


【解决方案1】:

问题可能与文件未打开有关。您应该始终检查文件是否已成功打开:

ifstream infile1("data31.txt");

if ( !infile1 )
{
    // Failed to open data31.txt
    return -1;
}

或者您可以使用显式函数而不是重载operator!

if ( infile1.fail() ) 
{
    return -1;
}

【讨论】:

    【解决方案2】:

    您得到的错误是什么?通过检查 infile.is_open() 函数确保文件已打开。你可以在这里找到示例代码:

    http://www.cplusplus.com/reference/iostream/ifstream/is_open/

    你也可以查看这个帖子:

    Using C++ ifstream extraction operator>> to read formatted data from a file

    它有一个使用 ifstream 的有用说明。

    【讨论】:

      【解决方案3】:

      代码可能存在的问题:

      1. Unopenable file/unopened file
      2. Unopenable file/unopened file
      3. Unopenable file/unopened file
      4. Unopenable file/unopened file
      

      如何解决这个问题?遵循@MaximSkurydin 的代码。

      【讨论】:

        猜你喜欢
        • 2013-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多