我正在尝试将整数转换为存储在 char *s
中的数字字符串。
char* ItoA(int n, char *s){
int mod = n;
for(int x = 1; x <= sizeof(n) + 2; x++){
int digit = mod % 10;
s[x-1] = digit;
mod = mod / 10;
}
return s;
}
void main(){
int n = 12345;
char s3;
// should print 12345
cout << "\n" << ItoA(n, &s3);
cin.get();
}
我知道我的符号有问题,因为我一直在 main 中得到一个垃圾数组作为输出。为什么我得到的是垃圾而不是“12345”?
最佳答案
问:为什么我得到的是垃圾而不是“12345”?
你正在使用 &s3
就好像它是一个字符数组。
使用:
int main(){
int n = 12345;
char s3[20]; // Use an array of characters large enough to hold the number.
// should print 12345
cout << "\n" << ItoA(n, s3);
cin.get();
}
此外,我不清楚您使用下面的 sizeof(n)
的逻辑是什么:
for(int x = 1; x <= sizeof(n) + 2; x++)
关于c++ - 使用 char* 存储整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28287286/