如何将101011010分别存储到数组中
How can I store 101011010 to array respectively?
例如
如果我输入一个数字,例如101011010
输入]
101011010
我想将数字存储到如下所示的数组中
结果]
数组[0] = 1 数组[1] = 0 数组[2] = 1 数组[3] =0 数组[4] = 1
数组[5] = 1 ...
我知道如何声明数组或 for 循环。好像有某种可以在C++库中帮助我的函数。=(
将包含数字的字符转换为实际数字的最简单方法是其他响应中已经提到的方法:
char ch = '3';
int number = ch - '0';
这是有效的,因为数字字符在 ASCII 表中具有连续的代码。
如果你有一个包含数字的字符串,并且你想把所有这些数字提取到一个数组中,你有几个选择,这取决于你实际想要使用/学习多少C++。
使用 C 样式数组
std::string str = "101011010";
// you must be sure somehow that the array is big enough
int arr[100] = { 0 };
for(std::string::size_type i = 0; i < str.size(); ++i)
{
arr[i] = str[i] - '0';
}
您必须正确管理该 C 样式数组的大小。
实际上开始使用C++而不仅仅是C
std::vector<int> arr (str.size());
for(std::string::size_type i = 0; i < str.size(); ++i)
{
arr[i] = str[i] - '0';
}
std::vector
更容易使用,您不必在编译时知道它的(最大(大小。
一些C++,甚至一些C++11
std::vector<int> arr (str.size());
std::transform(str.begin(), str.end(), arr.begin(),
[](std::string::value_type ch) { return (ch - '0'); });
再做一些C++11,并编译时间数组大小,以防您从1中错过它。
std::array<int, 16> arr;
std::transform(str.begin(), str.end(), arr.begin(),
[](std::string::value_type ch) { return (ch - '0'); });
与第一种情况一样,数组的大小是constexpr
的,因此您必须知道字符串的最大长度,并注意不要写入超过数组大小。与 C 样式数组不同,std::array
有一个方法at()
,它会执行边界检查,并在尝试访问数组大小之外的元素时引发异常。
相关文章:
- 多维数组存储三种不同的数据类型?
- C++将原始字符数组存储在元组中
- 将十六进制字符数组存储在字节数组中,而无需更改为 ASCII 或其他任何东西
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- 如何将元素的索引从2D数组存储到1D数组中,然后交换这些值
- 如何将JSON数组存储在Arduino程序中
- 如何在AVR(例如:ATMega)或Arduino微控制器上制作2D PROGMEM阵列的1D PROGMEM数组(存储
- 使用 char 数组存储数据
- 使用平面数组存储的元组容器
- 数组 存储并要求用户搜索它
- 将值从一个 char 数组存储到另一个 char 数组
- 如何使字符串数组存储在向量中
- 将构造的静态数组存储在多个文件中的内存中
- 将整数数组存储在堆上并通过指针访问它们
- c++声明一个数据类型的字节数组,该数组存储在字符串中
- 使用指针数组存储阶乘计算的所有中间结果
- 使用异构数组存储不同的子类
- 读取文件内容,存储在数组中,向数组添加更多内容,然后将新数组存储在文件C++中
- 尝试将复杂数组存储到类 c++ 中
- 在字节数组存储中嵌入 int/string