从文件使用c ++的3d矢量

时间:2014-08-27 09:14:07

标签: c++ file-io vector

文本文件的数据如下所示。

.i 8
.o 8
00000000 00000000
00010001 00010010
00000100 01000000

请注意,在第1列中,0和1是独立的。我想将此数据解析为 3d vector - 每行3行2列和8个元素列为整数类型并显示向量。

我尝试了这样的代码

 #include <string>
 #include <iostream> 
 #include <sstream>
 #include <vector>
 #include <bitset>
 #include <fstream>
 #include <stdio.h>
 #include <stdlib.h>
 #include "Line12.hpp"

 using namespace std;
 void printLine12(Line12 line1)
 { 
     cout << "first:" << line1.getFirst() << endl;
     cout << "in:" << line1.getIn() << endl;       
 }
 int main()
 {
     std::vector<Line12> lines12;
     std::vector<std::vector<std::bitset<8> > > a;

std::ifstream in("C:/Users/Lenovo/Desktop/hwb8_64.pla");
std::string Line;

for(int i=1; i<=258;i++)
{
  std::getline(in,Line);
  if(i==1 || i==2)
  {
  Line12 s(Line);
  lines12.push_back(s);
  }
  else if(i >= 3 && i<=258)
  {
    a.push_back(std::vector< std::bitset<8> >());
    std::istringstream iss(Line);
    std::string bits;
    while (iss >> bits)
    {
    a.back().push_back(std::bitset<8>(bits));
    }     
  }               
}
system ("PAUSE");
for(int i=1; i<=258;i++)
{
  if(i==1 || i==2)
  {
  Line12 s1 = lines12.at(i);
  printLine12(s1);
  } 
  else if(i>=3 && i<=258)
  {
   for (int x = 0; x < a.size(); ++x)
   {
    for (int y = 0; y < a[i].size(); ++y)
    {
        for (int z = 7; z >= 0; --z)
        {
            std::cout << a[x][y][z];
        }
        std::cout << " ";
    }
    std::cout << std::endl;
  }
 } 
}      
system ("PAUSE");
return 0;
}

我收到了错误std::invalid_argument --> bitset::_M_copy_from _ptr

如何删除此错误?

1 个答案:

答案 0 :(得分:0)

Live demo link.

#include <string>
#include <iostream> 
#include <sstream>
#include <vector>
#include <bitset>
#include <fstream>

int main()
{ 
    std::vector< std::vector< std::bitset<8> > > v3d;
    std::ifstream in(path_to_file);
    std::string line;

    while (std::getline(in, line))
    {
        v3d.push_back(std::vector< std::bitset<8> >());
        std::istringstream iss(line);
        std::string bits;
        while (iss >> bits)
        {
            v3d.back().push_back(std::bitset<8>(bits));
        }
    }

    for (int i = 0; i < v3d.size(); ++i)
    {
        for (int j = 0; j < v3d[i].size(); ++j)
        {
            for (int k = 7; k >= 0; --k)
            {
                std::cout << v3d[i][j][k];
            }
            std::cout << " ";
        }
        std::cout << std::endl;
    }
}