0

This is the first time i ran into this problem so I have no idea how to fix it. EDIT: Nevermind. Look like an off by one error in my constructor caused this to happen somehow


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

my text file is just 1 line: 5

Thuan Trinh
  • 75
  • 1
  • 3
  • 9
  • Can you post constructor and destructor for `GraphM` and the rest of the `for` loop. The first call to `G.buildGraph()` won't set `eof()` so a second iteration of the loop will be performed. – hmjd Oct 18 '12 at 08:06

3 Answers3

4

The problem might be related to the file not being open. You should always check whether a file has been successfully opened:

ifstream infile1("data31.txt");

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

or you can use an explicit function instead of overloaded operator!

if ( infile1.fail() ) 
{
    return -1;
}
Maksim Skurydzin
  • 10,301
  • 8
  • 40
  • 53
1

What is the error that you get? Make sure that the file is open by checking the infile.is_open() function. you can find the sample code here:

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

You can also check this thread:

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

It has a useful instructions for using ifstream.

Community
  • 1
  • 1
manman
  • 4,743
  • 3
  • 30
  • 42
0

Possible problems with the code:

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

How to get around this problem? Follow @MaximSkurydin's code.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78