用char []和int

时间:2020-04-25 19:21:54

标签: c string

我想做的是从两个变量中创建一个字符串,以便可以在其上使用各种string.h函数。 到目前为止,这是我得到的,但是它返回一个空字符串。

size_t length = strlen(name) + sizeof(int) + 1;
char *player = malloc(length);
snprintf(player, length, "%s %d\n", name, score);

并给出另一个具有相同格式的字符串,然后在它们上使用strcmp,如下所示:

if (strcmp(line, player) < 0)
        {
            fprintf(fcopy, "%s %d\n", name, score);

        }
        else
        {
            fputs(line, fcopy);
        }

我要编写的函数从txt文件中获取“行”输入,其结构如下:

约翰50

亚伦45

所以我需要播放器字符串具有相同的格式。 希望这很清楚,对不起,但是我是一个新手,我才刚开始使用C并使用stackoverflow。

1 个答案:

答案 0 :(得分:1)

如果您使用动态分配,最简单的方法就是让snprintf为您提供长度:

// calling with NULL,0 and it returns the count of character that
// __would__ have been written to the buffer
int len = snprintf(NULL, 0, "%s %d\n", name, score);
char *player = malloc(len + 1);
snprintf(player, len, "%s %d\n", name, score);
...
free(player); // remember to pick out the trash
相关问题