c++ - 我无法弄清楚为什么在使用 ifstream 时出现段错误

标签 c++ eclipse

我是 C++ 的新手。我正在尝试打开一个文件并将其传递给另一种方法,以便我可以从 ifstream 中读取数据。这是打开文件的方法。

int main() {
// part 1
    ifstream infile1("data31.txt");
    if (!infile1) {
       cout << "File could not be opened." << endl;
       return 1;
   } 

//for each graph, find the shortest path from every node to all other nodes
    for (;;) {
       int data = 0;
       GraphM G;
       G.buildGraph(infile1);
       if (infile1.eof())
           break;

    }

    return 0;
}'

然后我在另一个名为 GraphM 的类中有另一个方法,我是这样实现的:

void GraphM::buildGraph(ifstream& infile1) {
   int data = 0;
   infile1 >> data;
   cout << "data = " << data << endl;
}

但是当我尝试将读取的数字存储到数据变量中时,出现了段错误。谁能帮我弄清楚出了什么问题?

提前致谢。

最佳答案

我无法解释段错误,但使用 infile.eof() 来中断并不是一个好的策略。参见 Why is iostream::eof inside a loop condition considered wrong?了解更多详情。

我建议使用:

int main() {

   ifstream infile1("data31.txt");
   if (!infile1) {
      cout << "File could not be opened." << endl;
      return 1;
   } 

   // Continue reading as long as the stream is valid.
   for (; infile1 ;) {
      GraphM G;
      G.buildGraph(infile1);
   }

   return 0;
}

void GraphM::buildGraph(ifstream& infile1) {
   int data = 0;
   if ( infile1 >> data )
   {
      // Data extraction was successful.
      cout << "data = " << data << endl;
   }
}

关于c++ - 我无法弄清楚为什么在使用 ifstream 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35216168/

相关文章:

c++ - 如何判断一个类是否实现了 != 运算符重载?

c++ - 传递初始数组值使用大括号

java - 自动建议出现时 Eclipse 意外关闭

android - 使用 ant 构建时验证错误,从 Eclipse 构建时正常

c++ - 为什么这个浮点运算编译得如此奇怪(没有优化)?

c++ - 二叉搜索树查找和删除 [C++]

c++ - Node js 原生模块,从 Objective-C block 事件监听器触发回调不起作用

java - 如何将 JAR 文件添加到 Eclipse 中的 web-inf/lib 文件夹?

Eclipse egit push 到两个远程仓库

java - 为什么 Cobertura 似乎切换了我的 Eclipse 的 Java 版本?