从文本文件中读取c++

Reading from text files C++

本文关键字:读取 c++ 文件 文本      更新时间:2023-10-16

我有一个包含三列数字的文本文件;一列代表一组点的x,y,z坐标。所有数字都在01之间

我已经创建了以下结构:
typedef struct 
{
    double xcd, ycd, zcd;
} point; 

我想创建一个大小为n的point类型的结构数组。然后我要逐行扫描文本文件,对于n粒子,我要将n行的三个数字分别放入xcd, ycdzcd的位置。

告诉我是否有一些有效的方法来做这件事。

ifstreamvector和其他各种装备,简单地像以前展示过的那样做。

ifstream infile("myfile.txt");
// check if file opened successfully
if (!infile) {
    cerr << "failure, can't open file" << endl;
    cin.get();
    return EXIT_FAILURE;
}
// the container in which we will store all the points
vector<point> points;
// a temporary point to hold the three coords in while we read them all
point tmp;
// read in three doubles from infile into the three coords in tmp
while (infile >> tmp.xcd && infile >> tmp.ycd && infile >> tmp.zcd)
    // add a copy of tmp to points
    points.push_back(tmp);

这将读取三个双精度并将它们放入point中,然后将point的副本放入points中。但是,如果文件模数3中的数字个数不为0,它将停止并且不将不完整点添加到points

使用std::fstream

如果你确定文件是正确的:

struct Point { 
    double xcd, ycd, zcd;
};
// btw this is how you should declare a structure in C++,
// the way you shown is rather characteristic to C and only used there
Point tab[N];
void foo() {
    std::ifstream f("file.txt");
    for (int i=0; i<N; ++i) {
        f >> tab[i].xcd >> tab[i].ycd >> tab[i].zcd;
    }    
}

如果您不确定文件是否存在,并且不确定是否包含这个粒子数,则应该在每次读取尝试后检查f.fail()

我更喜欢使用标准的泛型算法来编写我自己的循环:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <fstream>
typedef struct 
{
  double xcd, ycd, zcd;
} point;
std::istream& operator>>(std::istream&is, point& pt)
{
  return is >> pt.xcd >> pt.ycd >> pt.zcd;
}
int main(int ac, char **av) {
  std::ifstream f("file.txt");
  std::vector<point> v;
  std::copy(
    std::istream_iterator<point>(f),
    std::istream_iterator<point>(),
    std::back_inserter(v));
}

另一种设计是在point结构中重载流提取操作符:

struct Point
{
    double x;
    double y;
    double z;
    friend istream& operator>>(istream& inp, Point& p);
}
istream& operator>>(istream& inp, Point& p)
{
    inp >> x;
    inp >> y;
    inp >> z;
    inp.ignore(100000, 'n');
    return inp;
}

用法:

ifstream myfile("data.txt");
Point p;
vector<Point> point_container;
while (myfile >> p)
{
    point_container.push_back(p);
}