如何用两列C ++填充文本文件中的向量

时间:2017-02-22 12:37:35

标签: c++

我是C ++的新手,我正在尝试从文本文件中读取2d平面中的点矢量。为此,我首先创建一个由两个值(x,y)组成的结构,称为point。然后这些点的向量称为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);

道歉,如果这很简单,但对我来说不是!下面发布的是一个只有6分的txt文件的例子。

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);

}

2 个答案:

答案 0 :(得分:4)

您可以在循环中使用普通输入运算符>>

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 :(得分:0)

  1. 使用std::getline()

  2. 读取一行
  3. 按照提到的here

  4. 拆分字符串中的空格
  5. 将每个元素推送到您的向量。

  6. 重复下一行,直至文件结尾