2013-06-11 3 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

'연산자'(istream & is, Point & p)'에'is' 대신'cin'을 사용하고 있습니다. – dyp

+0

@DyP 답변이어야합니다. – Angew

+0

@DyP, 감사합니다! 나는 눈먼 나귀 야 ....))) –

답변

4

operator >> (istream& is, Point& p)is 대신 cin을 사용하고 있기 때문입니다.

루프를 실행하기 전에 is은 정상이므로 무한 루프가 발생하고 루프는 is을 변경하지 않습니다.

관련 문제