Simon
Simon

Reputation: 5039

C++ : reading content from a file in a specific format

I have a file which contains pixel coordinates in the following format :

234 324
126 345
264 345

I don't know how many pairs of coordinates I have in my file.

How can I read them into a vector<Point> file? I am a beginner at using reading functions in C++.

I have tried this but it doesn't seem to work :

vector<Point> iP, iiP;

ifstream pFile, rFile;
pFile.open("D:\\MATLAB\\WORKSPACE_MATLAB\\pData.txt");
rFile.open("D:\\MATLAB\\WORKSPACE_MATLAB\\rData.txt");

string rBuffer, pBuffer;
Point rPoint, pPoint;

while (getline(pFile, pBuffer))
{
    getline(rFile, rBuffer);

    sscanf(rBuffer.c_str(), "%d %d", rPoint.x, rPoint.y);
    sscanf(pBuffer.c_str(), "%d %d", pPoint.x, pPoint.y);

    iP.push_back(pPoint);
    iiP.push_back(rPoint);
}

I receive some odd memory errors. Am I doing something wrong? How can I fix my code so that it can run?

Upvotes: 0

Views: 124

Answers (2)

Simon
Simon

Reputation: 5039

Thanks to Chris Jester-Young and enobayram I have managed to solve my problem. I have added bellow my code.

vector<Point> iP, iiP;

ifstream pFile, rFile;
pFile.open("D:\\MATLAB\\WORKSPACE_MATLAB\\pData.txt");
rFile.open("D:\\MATLAB\\WORKSPACE_MATLAB\\rData.txt");
stringstream ss (stringstream::in | stringstream::out);

string rBuffer, pBuffer;


while (getline(pFile, pBuffer))
{
    getline(rFile, rBuffer);

    Point bufferRPoint, bufferPPoint;

    ss << pBuffer;
    ss >> bufferPPoint.x >> bufferPPoint.y;

    ss << rBuffer;
    ss >> bufferRPoint.x >> bufferRPoint.y;

    //sscanf(rBuffer.c_str(), "%i %i", bufferRPoint.x, bufferRPoint.y);
    //sscanf(pBuffer.c_str(), "%i %i", bufferPPoint.x, bufferPPoint.y);

    iP.push_back(bufferPPoint);
    iiP.push_back(bufferRPoint);
}

Upvotes: 0

C. K. Young
C. K. Young

Reputation: 223003

One way to do it is to define a custom input operator (operator>>) for your Point class, then use istream_iterator to read the elements. Here's a sample program to demonstrate the concept:

#include <iostream>
#include <iterator>
#include <vector>

struct Point {
    int x, y;
};

template <typename T>
std::basic_istream<T>& operator>>(std::basic_istream<T>& is, Point& p) {
    return is >> p.x >> p.y;
}

int main() {
    std::vector<Point> points(std::istream_iterator<Point>(std::cin),
            std::istream_iterator<Point>());
    for (std::vector<Point>::const_iterator cur(points.begin()), end(points.end());
            cur != end; ++cur) {
        std::cout << "(" << cur->x << ", " << cur->y << ")\n";
    }
}

This program takes the input, in the format you specified in your question, from cin, then outputs the points on cout in (x, y) format.

Upvotes: 6

Related Questions