c - 在循环中将整数作为字符串附加到 char[]

标签 c char int

给出以下示例。

我通过向每个字符的数字表示形式添加一个 secret 数字来对字符串进行编码。

A -> 41 = 65 + secret
B -> 42 = 66 + secret
1 -> 31 = 49 + secret
2 -> 32 = 50 + secret
and so on

所以结果将有几个数字。我可以使用打印它们

for(int i=0; i<len; i++) {     
    int e = ( (int)caracter + pub ) % mod;
    printf("%d ", e);                        
} 

但是我如何将所有这些数字添加到像这样的字符串中

123465 123466 123449 123450

谢谢

最佳答案

https://www.tutorialspoint.com/c_standard_library/c_function_sprintf.htm

http://www.cplusplus.com/reference/cstdio/sprintf/

注意缓冲区大小。你可以做溢出。

示例:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int e[5] = {12,34,78,33,15577};
    int n = 5;
    int len = 0;
    int i = n;
    while (i--) len += snprintf(NULL, 0, "%d ", e[i]);
    char* str = (char*)malloc(sizeof(char)*len);
    char* str_cur = str;
    i = n;
    while (i--) str_cur += sprintf(str_cur, "%d ", e[i]);
    printf("%s",str);
    return 0;
}

返回

15577 33 78 34 12

关于c - 在循环中将整数作为字符串附加到 char[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53939834/

相关文章:

C FILE指针,为什么不直接使用FILE类型呢?

c - 为什么我会收到 "assignment from incompatible pointer type"错误?

c++ - 为什么 getline() 跳过输入,即使在 cin.clear() 之后?

swift - 在 SpriteKit 中创建随机数

MySQL:插入 float ,最后是一个整数

c - 如何将 int 添加到先前创建的包含字符串的缓冲区

C编程: Segmentation fault (core dumped)

c - 我的 sscanf 如果陷入无限循环,我该如何修复它

C:如何为char数组动态分配和释放内存?

c# - 有没有更好的方法从 C# 中的整数中删除字符?