2016-05-11 80 views
0

我在读取文件和保存回2D矢量时遇到了问题。这是写在文件上的函数:从文件中读取整数并将其存储在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(); 
} 

这就简单地为每行写一个随机数(height * width * 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(字节数*线)到开始读取相乘,所述结构框架是只有一个2D矢量来存储这些值。我必须用offset来做到这一点,因为下一步将进行这种多线程,每个知道帧数的线程都应该计算右偏移量以开始读取和存储。

+0

抛出任何错误,什么? – Vtik

+0

偏题:建议编写二进制文件,而不是文本文件。更小的文件(6x),更容易预测边界(但在这里限制边界你已经做得很好),并且你不必从文本转换为整数。应该给你一个很大的速度提升,因为你可以将整个文件整理成一个大字节的数组,然后在多个线程之间进行划分。 – user4581301

+1

无论如何,一个块或忙碌旋转应该是一个容易发现的问题开发环境随附的调试器。 – user4581301

回答

0

假设该文件是这样的:

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'; 
    } 
} 
相关问题