Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 向int字符串添加前缀_C_String_Char_Int - Fatal编程技术网

C 向int字符串添加前缀

C 向int字符串添加前缀,c,string,char,int,C,String,Char,Int,是否有一个函数可以用来转换类似intnum=12编码为字符串 基本上我有一个存储字符串的循环。该字符串的前缀必须是int num。其中,num每次循环一次时都会不断增加 我想在hello world的原始字符串中添加一个前缀,使输出看起来像12。你好,世界 char *original = "Hello world"; char *dot_space = ". "; int num = 0; while (num < 200) { char *num_string = ""; //

是否有一个函数可以用来转换类似
intnum=12编码为字符串

基本上我有一个存储字符串的循环。该字符串的前缀必须是
int num
。其中,
num
每次循环一次时都会不断增加

我想在
hello world
的原始字符串中添加一个前缀,使输出看起来像
12。你好,世界

char *original = "Hello world";
char *dot_space = ". ";
int num = 0;
while (num < 200) {
    char *num_string = ""; // Some how I convert the num to a string?
    char *new_string = malloc(sizeof(char) * strlen(original) + strlen(num_string) + strlen(prefix) + 1;
    strcpy(new_string, num_string);
    strcpy(new_string, prefix);
    strcpy(new_string, original);
    printf("%s\n", new_string);

    num++;
}
char*original=“Hello world”;
char*dot_space=“.”;
int num=0;
while(num<200){
char*num_string=“”;//如何将num转换为字符串?
char*new_string=malloc(sizeof(char)*strlen(original)+strlen(num_string)+strlen(prefix)+1;
strcpy(新字符串、num字符串);
strcpy(新字符串,前缀);
strcpy(新字符串,原件);
printf(“%s\n”,新字符串);
num++;
}

sprintf(buffer,“%d.%s”,num++,str);

您可以使用
sprintf
生成连接字符串。当然,诀窍是知道数字的长度。我们可以使用本地数组,然后将其复制到最终字符串

差不多

// reserve 4 characters for each octet in the `int`
char num_string[sizeof num * CHAR_BIT / 2];

// sprintf returns the length of the string!
int num_len = sprintf(num_string, "%d", i);

// size of char is exactly 1
char *new_string = malloc(strlen(original) + strlen(prefix) + num_len + 1);

// then concatenate all with one sprintf
sprintf(new_string, "%s%s%s", num_string, prefix, original);

当然,如果您有幸使用Glibc,比如说Linux;或者BSD,并且不必费心编写随处可见的便携软件,那么您可以使用asprintf

// must be before the include
#define _GNU_SOURCE
#include <stdio.h>

char *new_string;
asprintf(&new_string, "%d%s%s", i, prefix, original);
//必须在包含之前
#定义GNU源
#包括
char*新的_字符串;
asprintf(&new_字符串,“%d%s%s”,i,前缀,原始);
这对应于上面的4行



请注意,原来的
strcpy
x3方法也会失败;
strcpy
总是从目标缓冲区的第一个字符开始覆盖;调用应该是
strcpy
strcat
strcat
,您知道
sprintf()
?你的意思是你的前缀是转换后的数字还是有一个额外的前缀?否则
num\u string
prefix
应该是一样的。在向另一个字符串添加字符串时,你需要
strcat
。只有第一个可以用
strcpy
复制。我不会认为这非常有用。唯一能让你这么做的是NSE这里是OP想知道一个实际转换,而不是在C.@ RoFLCOPTE4中怎么做,如果OP问“有一个函数将整数转换成一个字符串”,我们可以假设它也包括如何使用它。如果你幸运地使用C++,这会在手腕的两个闪烁中掉出来。