将字符串存储为整数数组
store a string to integer array
我正在尝试将一个数字( 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)。
相关文章:
- 从二进制文件中读取整数数组
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 从两个 4x64 位整数数组中获取取模
- 字符到整数数组
- 从函数参数 [C++] 复制整数数组
- 指向整数数组和打印总和的指针
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 线程安全整数数组?
- 整数数组中最长的回文
- 在大整数数组中查找子数组
- 查找整数数组中最接近的数字
- 创建<int>对整数数组指针的矢量引用 (C++)
- 整数指针数组的元素是否可以指向整数数组?
- 如何将整数数组相乘得到一个数字?
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 将文本文件读入整数数组