拆分一个二进制数字符串,并将其存储在c++中的int类型数组中

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

本文关键字:c++ 存储 中的 int 数组 类型 一个 字符串 二进制数 拆分      更新时间:2023-10-16

我想拆分一个二进制数字字符串,例如"0101011010",并将其存储在int数组中。应该在c++中完成。

这就是我尝试过的。

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

这样做的问题是,如果字符串的开头包含"0",则在转换为int时会漏掉它。

您可以执行类似的操作,将其推入intvector

#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');}
}

但如果你真的想使用数组,你可以这样做:

#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;}
}
while(inp>=0){
   if(inp==0){
     a[i]=0;
     break;
  }
  //...
}

如果输入为零,则i既不会递增,也不会更改输入,因此会进入一个无限循环。尝试在if-部分中修改inputi

/编辑:好吧,你做这件事的方式真的太复杂了。我不是copy&粘贴代码,但这是我的做法:

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