tags:

views:

132

answers:

3

I'm doing an exercise where I store coordinates into a .txt file called mydata, and then read it back from that file. However, I"m having trouble reading it back.

code:

#include "std_lib_facilities.h"

// Classes----------------------------------------------------------------------

struct Point{
Point(int a, int b):x(a), y(b) {};
Point(){};
int x;
int y;
};

// Main-------------------------------------------------------------------------

int main()
{
    vector<Point> original_points;
    vector<Point> processed_points;
    cout << "Please enter 7 coordinate pairs.\n";
    int x, y;
    while(cin >> x >> y){
              if(x == -1 || y == -1) break;
               original_points.push_back(Point(x, y));}
    cout << "Please enter file to send points to.\n";
    string name;
    cin >> name;
    ofstream ost(name.c_str());
    if(!ost)error("can't open output file", name);
    for(int i = 0; i < original_points.size(); ++i)
            ost << original_points[i].x << ',' << original_points[i].y << endl;
    ost.close();
    cout << "Please enter file to read points from.\n";
    string iname;
    cin >> iname;
    ifstream ist(iname.c_str());
    if(!ist)error("can't write from input file", name);
    while(ist >> x >> y) processed_points.push_back(Point(x, y));
    for(int i = 0; i < processed_points.size(); ++i)
            cout << processed_points[i].x << ',' << processed_points[i].y << endl;
    keep_window_open();
}

To test to see if the data is being read from the file I am pushing it back into a processed points vector, but when I run the program and enter points, it doesn't output any points from the processed_points vector. I think the problem is in the...

while(ist >> x >> y)

and this isn't the correct way to read from a file. Any help would be appreciated, thanks.

+3  A: 

The , you're emitting in the line

        ost << original_points[i].x << ',' << original_points[i].y << endl;

is what stands in your way, since you're NOT reading it back! Either use a space instead of that comma, or, DO read it back...

Alex Martelli
+1  A: 

If you don't need to force reading new line:

while( (ist >> x) && ist.ignore(1024,',') && (ist >> y))
    processed_points.push_back(Point(x, y));

The best way is to read whole line first, and then use stringstream to parse the point.

string temp;
while( std::getline(ist,temp) )
{
     std::stringstream line(temp);
     if( (line >> x) && line.ignore(1024,',') && ( line >> y ) )
         processed_points.push_back(Point(x, y));
}
lionbest
A: 

The code (ist >> x >> y) is fine, except that the comma causes the istream into y to fail. The character is a comma, not a digit so the conversion fails. Alex is on the right track here.

Michael Mathews