[英]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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.