繁体   English   中英

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

[英]I can't figure out why I have a segmentation fault when using ifstream

我对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()中断不是一个好的策略。 请参阅为什么循环条件内的iostream :: eof被认为是错误的? 有关更多详细信息。

我建议使用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM