c - int 到 String 来连接?

标签 c

#include<stdio.h>
#include<string.h>

int main() {
    int num = 5;
    char hi[15] = "15";
    strcat(hi, num)

}

有什么方法可以轻松做到这一点吗?例如,我想将 num 变成一个字符串并将其连接起来,使其变为 155。

最佳答案

#include<stdio.h>
#include<malloc.h>
#include<string.h>

int findDigits(int n){

    int count = 0;

    //if it's a single digit
    if( (n/10) == 0){

        return 1;
    }

    while(n /= 10){

        count++;
    }

    return count;
} 

int main() {

    int num = 5;
    char hi[15] = "15";
    char* buf = NULL;

    int digits = findDigits(num);

    if(digits > 0){

        if( (buf = malloc(digits + 1)) == NULL){

            return -1;
        }

        if( (strlen(hi) + digits) >= sizeof(hi) ){

            free(buf);
            return -1;
        }

        sprintf(buf, "%d", num);
        strcat(hi ,buf);

        free(buf);
        printf("%s", hi);

        getchar(); 
    }
    else{

        return -1;
    }

    return 0;
}

关于c - int 到 String 来连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48557377/

相关文章:

c - fdim 首字母缩写词代表什么?

c - 我不明白为什么我的 C 程序运行一次正确,然后却给出了不需要的结果

c - 混杂模式下的数据包套接字仅接收本地流量

c - 为什么我的 8 位指针不能正确更新?

c - 如何修复由 -Wconversion 引起的错误?

c# - 如何从 C# 中以 Struct 作为参数调用 C 代码中的函数

c - 比较三个值的函数

c++ - 用C++编译器编译C99文件

c - 'sizeof' 对不完整类型问题的无效应用

c - 有没有更好的方法来使用 cmake 构建 C 项目?