拆分一个二进制数字符串,并将其存储在c++中的int类型数组中
split a string of binary numbers and store it an array of type int in c++
我想拆分一个二进制数字字符串,例如"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时会漏掉它。
您可以执行类似的操作,将其推入int
的vector
:
#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
-部分中修改input
和i
。
/编辑:好吧,你做这件事的方式真的太复杂了。我不是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
相关文章:
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- C++:将控制台输出存储在宏中更好吗
- 使用QProcess执行命令,并将结果存储在QStringList中
- 访问存储在向量C++中的结构的多态成员
- 如何从存储在std::映射中的std::集中删除元素
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 带结构的二维矢量:如何存储元素
- 添加存储在向量中的大整数的函数出现问题
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 在std::vector上存储带有模板的类实例
- 谷歌测试中的期望值存储在哪里
- 为什么C中的通用链表中存储的数据已损坏
- 在c++中获取两个大int,并将它们存储在数组中
- 在reactor中存储eventHandlers的最佳方式是什么