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

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

本文关键字:文件 读取 格式 定格 C++      更新时间:2023-10-16

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

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

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

一种方法是为Point类定义一个自定义输入运算符(operator>>),然后使用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上的点。

多亏了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);
}