gpt4 book ai didi

c - sprintf 反转 int 并存储为 char

转载 作者:行者123 更新时间:2023-11-30 14:34:24 24 4
gpt4 key购买 nike

我正在尝试将 int 数组存储为 str 并以相反的顺序显示它。只有在打印 str 时我才会得到垃圾。

我的代码有什么问题?

int main() {
int a[] = { 1, 2, 3 }; // Output should be 321 (char)
int size = sizeof(a) / sizeof(int);
char str[size + 1];
int i;
for (size = size - 1; size >= 0; size--) {
sprintf(&str[size], "%d", a[size]);
//printf("%c\n", str[size]);
}
printf("%s\n", str); // I get garbage.
}

最佳答案

我修改了您的解决方案,修复了几个错误。对于初学者来说,您不能假设您的整数数组仅保存单个数字值。

还有那个 for 循环:

for(size=size-1;size >= 0;size--)

看起来很可疑。 (索引变量是它的基础?)

简单的解决方案

这可能就是您的意思:

for(i = 0; i < size; i++) {
sprintf(&str[i],"%d", a[size-1-i]);
}
str[size] = '\0';

或者这个:

str[size] = '\0';
for(i = size-1; i <= 0; i--) {
sprintf(&str[i],"%d", a[size-1-i]);
}

更好的解决方案

如果 a 数组中的整数为负数,我不确定您期望做什么。因此 - 符号将被插入到 str 中。

我的解决方案将首先计算 a 中每个整数需要多少个字符。然后它将分配具有该长度的 str 缓冲区(对于空字符+1)。

然后我们利用 sprintf 的返回值来确定连接的位置。我们可以使用 strcat,但这可能更快。

int main() {

int j = 0;
int a[] = { 1,2,3 }; // Output should be 321 (char)

int size = sizeof(a) / sizeof(int);
int length = 1; // +1 for final null char

// Count the size of characters needed for each integer
// Do a dummy sprintf and use its return value to figure out how many chars are needed
for (int i = 0; i < size; i++) {
char tmp[sizeof(int) * 5]; // sizeof(int)*5 is big enough to hold any integer including a negative value
length += sprintf(tmp, "%d", a[i]); // utilize the return value from sprintf and add it to the running length
}

char str[length];
str[0] = '\0'; // initially null terminate our string

// reverse print chars from a into str
for (int i = 0; i < size; i++) { // use i as index variable, not size
j += sprintf(str + j, "%d", a[size - 1 - i]);
}
printf("%s\n", str);
}

关于c - sprintf 反转 int 并存储为 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59005124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com