0

I am fairly new to C++. I am trying to open a file and pass it to another method so that I can read the data from the ifstream. Here is the method that opens the file.

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

And then I have another method that is in another class called GraphM and I have implemented it this way:

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

But when I try to store the read number into a data variable, I get a segmentation fault. Can anyone help me figure out what is wrong?

Thanks in advance.

1 Answers1

1

I can't explain the segmentation fault but using infile.eof() to break is not a good strategy. See Why is iostream::eof inside a loop condition considered wrong? for further details.

I suggest using:

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;
   }
}
Community
  • 1
  • 1
R Sahu
  • 196,807
  • 13
  • 136
  • 247