C ++:以特定格式从文件中读取内容

时间:2012-10-07 06:10:38

标签: c++

我有一个文件,其中包含以下格式的像素坐标:

234 324
126 345
264 345

我不知道我文件中有多少对坐标。

如何将它们读入vector<Point>文件?我是在C ++中使用阅读功能的初学者。

我试过这个,但它似乎不起作用:

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

我收到一些奇怪的内存错误。难道我做错了什么?如何修复我的代码以便它可以运行?

2 个答案:

答案 0 :(得分:6)

一种方法是为operator>>类定义自定义输入操作符(Point),然后使用istream_iterator读取元素。这是一个演示概念的示例程序:

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

此程序以cin的格式输入您在问题中指定的格式,然后以(x,y)格式输出cout上的点。

答案 1 :(得分:0)

感谢Chris Jester-Young和enobayram,我设法解决了我的问题。我添加了下面的代码。

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