C++ 将字符串存储到整数数组
我试图将一个数字(12位)作为字符串读取,然后将其复制到一个整数数组中,但没有得到正确的结果 我的代码在这里:C++ 将字符串存储到整数数组,c++,visual-studio-2010,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 o
//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 ;
}
//头文件
#包括
#包括
//名称空间
使用名称空间std;
int main()
{
字符串输入;
做
{
cout>输入;
}而((input.length())!=12);
int code[11];//存储代码的数组
//将字符串更改为整数
int intVal=atoi(input.c_str());
//
对于(int i=12;i>=0;i--)
{
代码[i]=intVal%10;
intVal/=10;
coutcode
的长度为11,但您正在尝试访问for
循环中的索引12和11,这两个索引都不存在。其次,12位数字不适合常规32位整数,有符号32位整数的最大值为2147483647
尝试在uint64\u t
中使用并存储该值,并修复数组索引(长度应为12,索引应为0-11).code
的长度为11,但您试图访问for
循环中的索引12和11,这两个索引都不存在。其次,12位数字不适合常规32位整数,有符号32位整数的最大值为2147483647
尝试在uint64\u t
中使用并存储该值,并修复数组索引(长度应为12,索引应为0-11)。若要将字符串转换为int数组,请尝试:
std::string input = "123456789101";
int code[12];
for (int i = 0 ; i < 12 ; i++)
{
code[i] = input.at(i) - '0';
}
std::string input=“123456789101”;
int代码[12];
对于(int i=0;i<12;i++)
{
代码[i]=输入。在(i)-“0”;
}
此外,intvVal不够大,无法容纳123456789101
要将字符串转换为int数组,请尝试:
std::string input = "123456789101";
int code[12];
for (int i = 0 ; i < 12 ; i++)
{
code[i] = input.at(i) - '0';
}
std::string input=“123456789101”;
int代码[12];
对于(int i=0;i<12;i++)
{
代码[i]=输入。在(i)-“0”;
}
此外,intvVal不够大,无法容纳
123456789101
请比“不正确”更精确。到底什么是错误的。请比“不正确”更精确.到底是什么错了。谢谢,这似乎有效。但是,当我使用循环显示I<11时,它只显示到12345678910。为什么它不显示完整数字?input=“12345678910”;
有12个数字,你只循环11个数字出于某种奇怪的原因,我在shell上运行了它,它显示了正确的结果。所以,我想,我的visual studio是一团糟。Thanx!!感谢这似乎是可行的。但是,当我使用循环显示<11时,它只显示到12345678910。为什么它不显示完整的数字呢? input=“123456789101”
有12个数字,你只循环11个数字。出于某种原因,我在shell上运行了它,它显示了正确的结果。所以,我猜,我的visual studio是一团糟。Thanx!!