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