0

I learn the C++. Below my simple code, but I got a problem in the next code row:

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

In the specified line I receive the infinite loop. Why it occur? I expected to get 'eof' (i.e. !is) and quit from a cycle.

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

Thank you.

4

1 回答 1

4

因为在你的operator >> (istream& is, Point& p)你使用cin而不是is.

你总是会得到一个无限循环,is在你运行循环之前是可以的,并且循环不会改变is

于 2013-06-11T13:44:05.120 回答