如何使用两列C 从文本文件中填充向量

how to populate vector from text file with two columns C++

本文关键字:文本 文件 向量 填充 两列 何使用      更新时间:2023-10-16

我是C 的新手,并试图在2D平面中创建一个从文本文件读取的点。为此,我首先创建一个由两个称为点的值(x,y)组成的结构。然后将这些点的向量称为VEC。但是,我不确定在文本文件中以三列为单位时如何填充结构数据!第一列只是点的索引,第二列是x数据,第三列是y数据。我不知道VEC的大小,所以我尝试使用push_back(),这是我到目前为止所拥有的。

    int main(){
        struct point{
 std::vector<x> vec_x;
 std::vector<y> vec_y;
    };
    std::vector<point> vec;
    vec.reserve(1000);
    push_back();
    ifstream file;
    file.open ("textfile.txt");
        if (textfile.is_open()){

/* want to populate x with second column and y with third column */
        }
        else std::cout << "Unable to open file";
    }

我有以下评论的地方;

while( file  >> x ) 
vec.push_back (x);

while( file  >> y ) 
vec.push_back (y);

很抱歉,如果这很简单,但这对我来说不是!下面发布的是TXT文件的一个示例,只有6个点。

0 131 842
1 4033 90
2 886 9013490
3 988534 8695
4 2125 10
5 4084 474
6 863 25

编辑

while (file >> z >> x >> y){
    struct point{
        int x;
        int y;
    };
    std::vector<point> vec;
    vec.push_back (x);
    vec.push_back (y);
}

您可以在循环中使用普通输入操作员>>

int x, y;  // The coordinates
int z;     // The dummy first value
while (textfile >> z >> x >> y)
{
    // Do something with x and y
}

至于结构,我建议一些不同的方法:

struct point
{
    int x;
    int y;
};

然后具有结构的向量:

std::vector<point> points;

在循环中,创建一个point实例,初始化其xy成员,然后将其推回points向量。

请注意,上面的代码几乎没有错误检查或容错性。如果文件中存在错误,则更具体地说,如果格式存在问题(例如,一行中的一个额外数字,或一个数字,那么上面的代码将无法处理。为此,您可以使用std::getline读取整行,将其放入std::istringstream中,然后从字符串流中读取xy变量。


将所有内容放在一起,工作代码的简单示例(不处理无效输入)将是

之类的
#include <fstream>
#include <vector>
// Defines the point structure
struct point
{
    int x;
    int y;
};
int main()
{
    // A collection of points structures
    std::vector<point> points;
    // Open the text file for reading
    std::ifstream file("textfile.txt");
    // The x and y coordinates, plus the dummy first number
    int x, y, dummy;
    // Read all data from the file...
    while (file >> dummy >> x >> y)
    {
        // ... And create a point using the x and y coordinates,
        // that we put into the vector
        points.push_back(point{x, y});
    }
    // TODO: Do something with the points
}
  1. 使用std::getline()

  2. 读取一条线
  3. 如下所述,将字符串拆分为白色空间

  4. 将每个元素推向向量。

  5. 重复下一行,直到文件结束