在读取大容量数据的时候,前面的几行常常包括文件的说明,所以读取的时候应该去掉,而且我们经常需要读取文件中的指定列的数据。下面的例子演示了这个功能:
//定位到txt文件的某一行
ifstream & seek_to_line(ifstream & in, int line)
//将打开的文件in,定位到line行。
{
int i;
char buf[1024];
in.seekg(0, ios::beg); //定位到文件开始。
for (i = 0; i < line; i++)
{
in.getline(buf, sizeof(buf));//读取行。
}
return in;
}
int _tmain(int argc, _TCHAR* argv[])
{
//读取文件路径
std::string pts_filename = "E:/数据文件/20190718.txt";
std::vector<Point3D> pts;
{
std::ifstream pts_file;
pts_file.open(pts_filename);
seek_to_line(pts_file, 2); //定位到指定的行开始读取
if (!pts_file.is_open())
{
cout << "Unable to open myfile";
system("pause");
exit(1);
}
while (!pts_file.eof())
{
//先忽略前面的2列,从第三列开始读取,读取了3-5列x,y,z的数据保存到point3D中,然后
//当前行后面的数据全部忽略
for (Point3D pt; (((pts_file >> ws).ignore(numeric_limits<streamsize>::max(), ' ') >> ws).ignore(numeric_limits<streamsize>::max(), ' ') >> pt.x >> pt.y >> pt.z >> ws).ignore(numeric_limits<streamsize>::max(), '\n');)
{
pts.push_back(pt); //将数据保存下来
}
}
pts_file.close();
}
return 0;
}
由于后来需要用到一些windows的函数,出现了编译错误,参考了链接:https://blog.csdn.net/huixingshao/article/details/86534865。std::numeric_limits::max()使用的是STL中的z数值极限<Numeric Limits>,如果又添加了#include<windows.h>则会出现如下错误:
warning C4003: “max”宏的实参不足
error C2589: “(” : “::”右边的非法标记
因为需要把max用括号括起来避免和windows定义的宏混淆
(std::numeric_limits<double>::max)()
因为Windef.h中定义了
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
所以会产生编译错误。