【问题标题】:how to populate vector from text file with two columns C++如何用两列 C++ 从文本文件中填充向量
【发布时间】:2017-02-22 12:37:34
【问题描述】:

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

}

【问题讨论】:

    标签: c++


    【解决方案1】:

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

    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
    }
    

    【讨论】:

    • 感谢您的帮助!但是,我仍在为此苦苦挣扎。我已经编辑了这个问题,你能告诉我我是否在正确的轨道上吗?干杯!
    • @AngusTheMan 有一点是,但也有很多不是。请参阅我的更新答案以获取一个简单的示例程序。
    • 非常感谢!
    【解决方案2】:
    1. 使用std::getline()读取一行

    2. here所提到的那样将字符串拆分为空格@

    3. 将每个元素推送到您的向量。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多