Question

A rather quick question... I can't figure out why this loop never ends...

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
 //[city1][city2][distance]

 ifstream sourcefile;

 int data[50][50];



 sourcefile.open("a5.txt");
 if(!sourcefile)
 {
  cout << "file not found" << endl;
  return 1;
 }

 int temp1, temp2, temp3, check;

 char reader;

 check = 0;



 while(reader != 'Q')
 {
  sourcefile >> temp1;
  sourcefile >> temp2;
  sourcefile >> temp3;

  data[temp1][temp2] = temp3;

  cout << "data[" << temp1 << "][" << temp2 << "] = " << temp3 << endl;
  check++;

  if(check > 100)
  {
   cout << "overflow" << endl;
   return 1;
  }

  reader = sourcefile.peek();


 }



 return 0;
}

The input file

1 2 10
1 4 30
1 5 99    
2 3 50    
2 1 70    
3 5 10    
3 1 50    
4 3 20    
4 5 60    
5 2 40   
Q

The output:

data[1][2] = 10
data[1][4] = 30
data[1][5] = 99
data[2][3] = 50
data[2][1] = 70
data[3][5] = 10
data[3][1] = 50
data[4][3] = 20
data[4][5] = 60
data[5][2] = 40
data[0][2] = 40
data[0][2] = 40

...
... (repeats "data[0][2] = 40" about 60 more times)
overflow

Is this a case of peek getting a failbit character?

Was it helpful?

Solution

peek lets you see the next character, which I think in this case is the newline after the distance value. since it's not Q, the loop tries to read another three integer values, fails, and sets the error bit. peek, when there's a failure, returns EOF - so you never get to see the Q.

OTHER TIPS

Try the following before starting to read from the file.

sourcefile >> std::skipws;

It will cause whitespace such as line break to be ignored.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top