Convert string matrix

Hi guys, i need some help with something.

I have a matrix of strings, for example :

00000000001000100001100000100000 // pos 0 0
00000000100001000010100000100000 // pos 1 0
00000000001000100001100000100000 // pos 2 0.

How can i convert that matrix, in a matrix of int with 32 columns and 3 lines? Every bit = 1 column.


Thanks for help!
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
   stringstream in( "00000000001000100001100000100000 pos 0 0\n"
                    "00000000100001000010100000100000 pos 1 0\n"
                    "00000000001000100001100000100000 pos 2 0\n" );

   vector< vector<int> > M;
   string bits, junk;
   while( in >> bits && getline( in, junk ) )
   {
      vector<int> V;
      for ( char c : bits ) V.push_back( c != '0' );
      M.push_back( V );
   }

   cout << "Your matrix has " << M.size() << " lines and " << M[0].size() << " columns:\n";
   for ( auto row : M )
   {
      for ( auto i : row ) cout << i << ' ';
      cout << '\n';
   }
}


Your matrix has 3 lines and 32 columns:
0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 
0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 
Last edited on
Can you tell me why "c != '0' "? Thanks
The elements that make up that string are either '0' or '1' (as char variables).

The expression c != '0' initially yields a boolean answer (true or false). This is then implicitly cast to an integer (since that is the declared type of the elements of vector V - it is what you asked for), with false becoming 0 and true becoming 1.
c != 0 is an expression that evaluates to 1 (true) if c is not '0' and to 0 (false) if c is '0'. Therefore it turns the character code of c into an integer representing the value of the given binary digit character.

Alternatively, you could say c - '0' to get the same effect (and it works to get the value for any decimal digit character).
Last edited on
Topic archived. No new replies allowed.