2

一个相当快速的问题......我无法弄清楚为什么这个循环永远不会结束......

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

输入文件

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

输出:

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

这是偷看获得失败位角色的情况吗?

4

2 回答 2

4

peek 让您看到下一个字符,我认为在这种情况下是距离值之后的换行符。因为它不是 Q,所以循环尝试读取另外三个整数值,失败,并设置错误位。peek,当失败时,返回 EOF - 所以你永远看不到 Q。

于 2010-11-27T20:39:17.360 回答
0

在开始读取文件之前尝试以下操作。

sourcefile >> std::skipws;

它将导致诸如换行符之类的空白被忽略。

于 2010-11-27T20:42:06.217 回答