将字符串存储为整数数组

store a string to integer array

本文关键字:整数 数组 存储 字符串      更新时间:2023-10-16

我正在尝试将一个数字( 12 位数字)读取为字符串,然后将其复制到整数数组中,但没有正确处理。

我的代码在这里:

//header files
#include<iostream>
#include<string>
// namespace 
using namespace std ;
int main ()
{
    string input ;
    do
    {
        cout << "Make sure the number of digits are exactly 12 : ";
        cin >> input ;
    } while((input.length()) != 12 );
    int code[11] ; // array to store the code

    //change string to integer
    int intVal = atoi(input.c_str());

    //
    for (int i = 12; i >= 0 ; i--)
    {
        code[i] = intVal % 10;
        intVal /= 10 ;
        cout << code[i] ;
    }

    cout << endl ;
    //now display code
    for (int i = 0 ; i < 11 ; i++)
    {
        cout << code[i];
    }
    system ("pause") ;
    return 0 ;
}

所以,对于123456789101的基本输入,它应该存储在 code[] 数组中。

因此,当我显示代码循环时,我想确保它与123456789101相同。

但它即将到这个:

在代码期间

for (int i = 0 ; i < 11 ; i++)
{
cout << code[i];
}

它显示00021474836,我希望它向我显示数字!

要将字符串转换为 int 数组,请尝试:

std::string input = "123456789101";
int code[12];
for (int i = 0 ; i < 12 ; i++)
{
  code[i] = input.at(i) - '0';
}

此外,intvVal不够大,无法容纳123456789101

code的长度为 11,

但您尝试访问 for 循环中的索引 12 和 11,两者都不存在。其次,12 位数字不适合常规的 32 位整数,对于有符号的 32 位整数,最大值要么2147483647。

尝试使用 atol 并将值存储在 uint64_t 中,并修复数组索引(长度应为 12,索引应为 0-11)。