首页 > 解决方案 > 从 char[ ] 和 int 创建一个 char 字符串

问题描述

我想做的是用两个变量创建一个字符串 str ,这样我就可以在上面使用各种 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。

标签: cstring

解决方案


如果您使用的是动态分配,最简单的方法就是让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

推荐阅读