-3

This is what i have done so far , but then I am stuck on how to display x,y or count the number of points in that file. So let's assume we have these points with test1.txt :

0,1
0,4
6,3
2,4
5,4
5,6
6,4
5,4

Thank you

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

typedef struct
{
    int x;
    int y; 
} point;

int main()
{
    ifstream input;
    string filename;
    cout << "Enter the file name :" << endl;
    cin >> filename;
    input.open(filename.c_str());

    while(input.fail())
    {
        input.clear();
        cout <<"Incorrect filename, please enter again" << endl;
        cin >> filename ;
        input.open(filename.c_str()) ;
    }
    vector<point> points;
    point tmp;
    while (input >> tmp.x && input >> tmp.y)
    {
        points.push_back(tmp);
    };       
    cout << points.size() << endl;       
    return 0;
}
P0W
  • 42,046
  • 8
  • 62
  • 107
chichacail
  • 65
  • 1
  • 2
  • 6

2 Answers2

1

For given file format, you need to do like following :

char ch;  // dummy for comma

while (input >> tmp.x >> ch >> tmp.y)
{
    points.push_back(tmp);
}

input >> tmp.x && input >> tmp.y will fail for rhs operation as there's a char i.e. , not an int


You can also have a overloaded operator >> as friend too like following

struct point
{
    int x;
    int y; 

    friend std::istream& operator >>( std::istream& is, point& p )
    {   char ch;
        is >> p.x >> ch >> p.y ;
        return is ;
    }
} ;

Then, you can do

while (input >> tmp )
{
    points.push_back(tmp);
} 

Or use std::copy ,

std::copy( std::istream_iterator<point>(input),
       std::istream_iterator<point>(),
       std::back_inserter(points)
       ) ;

For displaying you can simply loop over vector points

for( size_t i = 0; i < points.size() ; ++i )
{
    std::cout << points[i].x << ',' << points[i].y << '\n';
}

or with C++11

for (const auto& i: points )
{
    std::cout << i.x << ',' << i.y << '\n';
}
P0W
  • 42,046
  • 8
  • 62
  • 107
0
while (!input.eof())
    {
        input >> tmp.x >> ch >> tmp.y;
        cout << tmp.x << " " << tmp.y << endl;
        points.push_back(tmp);


    };       

    cout << "Number of Points in this text File :" << points.size() << endl;
chichacail
  • 65
  • 1
  • 2
  • 6
  • You can post your working solution is its part from the answers provided. Also read this [Why is iostream::eof inside a loop condition considered wrong ?](http://stackoverflow.com/q/5605125/1870232) – P0W Feb 18 '15 at 00:48