从文件中读取整数并将其存储在二维矢量中

Reading integers from a file and store it in a 2D vector

本文关键字:二维 存储 读取 文件 整数      更新时间:2023-10-16

从文件中读取并保存回2D矢量时遇到问题。这是写在文件上的函数:

void create_input (int num_frames, int height, int width)
{
    ofstream GridFlow;
    GridFlow.open ("GridDB");
    for (int i = 0; i < num_frames; i++)
    {
        for (int j = 0; j < height; j++)
        {
            for (int k = 0; k < width; k++)
            {
                GridFlow << setw(5);
                GridFlow << rand() % 256 << endl;
            }
        }
    }
    GridFlow.close();
}

这只是为每行(高度*宽度*num_frames)写入一个随机数的次数。像这样:

    3
   74
  160
   78
   15
   30
  127
   64
  178
   15
  107

我想做的是从文件中读回,并将文件的不同块(宽度*高度)保存在不同的帧中。我试过这样做,但程序块没有任何错误:

vector<Frame> movie;
movie.resize(num_frames);
for (int i = 0; i < num_frames; i++)
{
    Frame frame;
    int offset = i*width*height*6;
    vector<vector<int>>tmp_grid(height, vector<int>(width, 0));
    ifstream GridFlow;
    GridFlow.open ("GridDB");
    GridFlow.seekg(offset, GridFlow.beg);
    for (int h = 0; h < height; h++)
    {
        for (int g = 0; g < width; g++)
        {
            int value;
            GridFlow >> value;
            tmp_grid[h][g] = value;
        }
    }
    frame.grid = tmp_grid;
    movie[i] = frame;
}

我使用了一个偏移量,每次乘以6(字节数*行)开始读取,结构Frame只是一个2D向量来存储值。我必须对偏移量进行处理,因为下一步将进行多线程处理,每个知道帧数的线程都应该计算正确的偏移量,以开始读取和存储。

假设文件如下:

1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,

以下是一种方法,说明如何将文件读取为矢量并将其输出到另一个文件:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
int main()
{
    using vvint = std::vector<std::vector<int>>;
    std::ifstream file{ "file.txt" };
    vvint vec;
    std::string line;
    while (std::getline(file, line)) {
        std::stringstream ss(line);
        std::string str_num;
        std::vector<int> temp;
        while (std::getline(ss, str_num, ',')) {
            temp.emplace_back(std::stoi(str_num));
        }
            vec.emplace_back(temp);
    }
    std::ofstream out_file{ "output.txt" };
    for (const auto& i : vec) {
        for (const auto& j : i) {
            out_file << j << ", ";
        }
        out_file << 'n';
    }
}