C++ 读写文本文件
1. 逐行读文本,文本以空格分隔
points.txt 文件内容如下:
index x1 y1 x2 y2
0 247 372 264 614
1 224 158 246 400
2 389 264 407 509
3 466 43 490 289
4 33 379 49 618
5 237 63 260 305
6 288 151 309 395
string filename="./points.txt";
fstream file;
vector<Point2f>vp1,vp2;
file.open(filename,ios_base::in);
string line;
while (!file.eof())
{
getline(file,line);
int index;
float x1,y1,x2,y2;
stringstream data(line);
data>>index>>x1>>y1>>x2>>y2;
vp1.push_back(Point2f(x1,y1));
vp2.push_back(Point2f(x2,y2));
}
file.close()
2. 逐行读文本,文本以","分隔
points.txt文件内容如下
index x1 y1 x2 y2
0,247,372,264,614
1,224,158,246,400
2,389,264,407,509
3,466,43,490,289
4,333,379,49,618
5,237,63,260,305
6,288,151,309,395
string filename = "./points.txt";
ifstream file(filename);
getline(file, line);
vector<string> vecIndex;
vector<double> vecx1,vecy1,vecx2,vecy2;
while (!file.eof())
{
string line;
if (getline(file, line)) {
stringstream ss(line);
string name;
double x1, yl, x2, y2;
string tmp;
int i = 0;
while (getline(ss, tmp, ',')) {
if (i == 0) { name = tmp; vecIndex.push_back(name); }
if (i == 1) { x1 = stod(tmp); vecx1.push_back(x1); }
if (i == 2) { yl = stod(tmp); vecy1.push_back(y1); }
if (i == 3) { x2 = stod(tmp); vecx2.push_back(x2); }
if (i == 4) { y2 = stod(tmp); vecy2.push_back(y2); }
i++;
}
}
}
file.close();