如何将101011010分别存储到数组中

How can I store 101011010 to array respectively?

本文关键字:数组 存储 101011010分      更新时间:2023-10-16

例如

如果我输入一个数字,例如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(),它会执行边界检查,并在尝试访问数组大小之外的元素时引发异常。