c - 从 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。
解决方案
如果您使用的是动态分配,最简单的方法就是让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
推荐阅读
- python-3.x - Pyinstaller 可执行文件因 pkg_resources.DistributionNotFound 错误而失败
- oauth-2.0 - oAuth with Microsoft Azure AD with azure GUEST 帐户与员工帐户
- arrays - 如何分离嵌套在 API 对象中的元素
- node.js - 从 Cognito 收到 JWT Token 后如何存储?通过 Cognito 托管 UI 登录
- powershell - 用于删除 Key Vault 机密的 PowerShell 脚本出现 409 冲突错误
- r - 按字数和堆积条形图
- android - 如何将 android 应用程序限制为特定品牌?
- flutter - Flutter:带安全区域的全底按钮
- sql - 将运行 SQL 语句中未使用的 CTE
- python - 使用 pip3 安装 awslocal CLI 后,在检查 CLI 选项时,我在终端中看到了这个:zsh: command not found: awslocal