c++ - 将字符串存储到整数数组

标签 c++ visual-studio-2010

我正在尝试读取一个数字(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

关于c++ - 将字符串存储到整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14543129/

相关文章:

c++ - 初始化 PhysFS 时出现问题

c++ - 为什么 std::remove_const 不删除 const 限定符?

c++ - 为什么当 MySQL 服务器不可用时我的程序崩溃

c++ - 如何让 CMenu 弹出菜单消失?

asp.net-mvc - 是否可以将 NUnit 集成到 Visual Studio 2010 中?

c++ - 使用Nsight调试导出DLL的非启动项目中的CUDA代码

c++ - 变量的 block 结构内存分配

C++属性类结构

C++ 游戏 - 发出父类信号,循环依赖问题

c++ - 如何重建旧库以在最新的 Visual Studio 上工作?