2013-06-11 53 views
0

我學習C++。在我的簡單代碼下方,但我在下一個代碼行遇到問題:爲什麼我在我的ifstream中有一個無限循環?

while(is >> p) vp.push_back(p); // TODO: here I have a problem... 

在指定的行中,我收到無限循環。爲什麼會發生?我期望得到'eof'(即!)並退出循環。

/* 
main.cpp 
© AB, 10/06/2013 
Chapter 10, Exercise 1. 
*/ 
//------------------------------------------------------------------------------------------------- 
#include <exception> 
#include <iostream> 
#include <string> 
#include <vector> 
#include<fstream> 
using namespace std; 
// Some structure... 
struct Point{ 
    int x, y; 
    Point(int xx, int yy): x(xx), y(yy){} 
    Point(): x(0), y(0) {} 
}; 
ostream& operator << (ostream& os, const Point& p){ 
    os << p.x << ',' << p.y; 
    return os; 
} 
istream& operator >> (istream& is, Point& p){ 
    char ch; 
    int x,y; 
    if((cin >> x >> ch >> y) && ch == ',') p = Point(x,y); 
    return is; 
} 
//================================================================================================= 
int main() 
    try{ 
     vector<Point> vp; 
     Point p; 
     while(cin){ 
      // Get some data... 
      cout << "x,y: "; 
      cin >> p; 
      if(cin) vp.push_back(p); 
     } 
     // print 
     for(int i = 0; i < vp.size(); ++i) cout << vp[i] << ' '; 
     cin.clear(); 
     string s; 
     // save to file 
     cout << endl << "Output file name: "; 
     if(!(cin >> s)) throw runtime_error("Invalid output file name."); 

     { // create output stream 
      ofstream os(s.c_str()); 
      if(!os) throw runtime_error("Can't open file: " + s); 
      for(int i = 0; i < vp.size(); ++i) os << vp[i] << ' '; 
     } // here ofstream erased 

     cout << "Read back..." << endl; 
     vp.clear();  
     ifstream is(s.c_str()); // create input stream 
     if(!is) throw runtime_error("Can't open file: " + s); 
     while(is >> p) vp.push_back(p); // TODO: here I have a problem... 
     for(int i = 0; i < vp.size(); ++i) cout << vp[i] << ' '; // print 
} 
catch(exception& e){ 
    cerr << e.what() << endl; 
    return 1; 
} 
catch(...){ 
    cerr << "Unknown exception." << endl; 
    return 2; 
} 

謝謝。

+4

因爲在你的'operator >>(istream&is,Point&p)'你正在使用'cin'而不是'is'。 – dyp

+0

@DyP這應該是一個答案。 – Angew

+0

@DyP,謝謝!我是一隻盲驢.... :))) –

回答

4

因爲在您的operator >> (istream& is, Point& p)中,您正在使用cin而不是is

你總是會得到一個無限循環,因爲is在你運行循環之前是可以的,循環不會改變is