简体   繁体   中英

split a string of binary numbers and store it an array of type int in c++

I wanted to split a string of binary numbers for example "0101011010" and store it in int array. Should be done in c++.

This is what i have tried.

 istringstream buffer(inputstring);
    int inp;
    buffer >> inp; 
    int a[10];
    int i=0;
    while(inp>=0){

       if(inp==0){
           a[i]=0;
         break;
      }
       else{
           int value = inp%10;
           a[i]=value;
           inp=inp/10;
      }; 
      i++
    }

The problem with this is, if the string contains "0" in the beginning, it is missed out when it gets converted to int.

while(inp>=0){
   if(inp==0){
     a[i]=0;
     break;
  }
  //...
}

If the input is zero, neither i gets incremented, nor the input is changed, so you run into an infinit loop. Try modifying input and i in the if -part also.

/Edit: ok your way of doing this is really over-complicated. I am not a big friend of copy&paste code but here is the way I would do it:

std::string str;
std::vector<int> number;
buffer >> str;  //Read the value into a string
for(char c : str) //Loop over all characters in the string
    number.push_back(c == '1' ? 1 : 0); //Write zero or one depending on character

You can do something like this pushing into a vector of int s:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string input="0101011010";
    vector<int> v;
    for(int i=0; i<input.size(); i++)
    {v.push_back(input[i]-'0');}
}

But if you really want to use an array you can do this:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    string input="0101011010";
    int arr[10];
    for(int i=0; i<10; i++)
    {arr[i]=input[i]-'0';}
    for(int i=0; i<10; i++)
    {cout << arr[i] << endl;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM