【问题标题】:3d vectors from file using c++使用c ++从文件中获取3d向量
【发布时间】:2014-08-27 09:14:06
【问题描述】:

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

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

请注意,第一列中的 0 和 1 是独立的。我想将此数据解析为 3d 向量 - 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 --&gt; bitset::_M_copy_from _ptr

如何消除此错误?

【问题讨论】:

  • 你想读入什么数据类型?因为您可以将其读入字符串数组。并阅读how to ask
  • 现在这只是一个要求。如果您需要解决问题的帮助,请发布您遇到问题的代码。你尝试了什么?
  • std::vector&lt;std::vector&lt;std::bitset&lt;8&gt;&gt;&gt;
  • 您是否在询问可以使用哪些库和函数从文件中读取?或者你知道那一点?
  • 我知道要使用哪些库。我想知道如何通过从文件中读取并显示它来为向量赋值。

标签: c++ file-io vector


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-07-04
    • 2013-08-02
    • 2018-03-10
    • 2012-10-25
    • 2017-10-19
    • 2016-03-19
    • 1970-01-01
    • 2017-03-22
    • 2019-01-21
    相关资源
    最近更新 更多