C++:以特定格式从文件中读取内容
C++ : reading content from a file in a specific format
我有一个文件,其中包含以下格式的像素坐标:
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);
}
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量