为什么我的ifstream中有一个无限循环?

时间:2013-06-11 13:35:31

标签: c++

我学习了C ++。在我的简单代码下面,但我在下一个代码行中遇到了问题:

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

谢谢。

1 个答案:

答案 0 :(得分:4)

因为您的operator >> (istream& is, Point& p)使用cin代替is

你总是会得到一个无限循环,因为is在运行循环之前是正常的,而循环不会改变is