我有一个文件,其中包含以下格式的像素坐标:
234 324
126 345
264 345
Run Code Online (Sandbox Code Playgroud)
我不知道我的文件中有多少对坐标.
如何将它们读入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);
}
Run Code Online (Sandbox Code Playgroud)
我收到一些奇怪的内存错误.难道我做错了什么?如何修复我的代码以便它可以运行?
一种方法是operator>>为您的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";
}
}
Run Code Online (Sandbox Code Playgroud)
此程序以您在问题中指定的格式输入输入,cin然后cout以(x,y)格式输出点.
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |