#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/