gpt4 book ai didi

C:按 int 追加字符串

转载 作者:行者123 更新时间:2023-11-30 18:55:05 25 4
gpt4 key购买 nike

我正在尝试获取一个字符串,并在其后面添加和 int。这是我现在的代码

int myint = 7;
string mystring = "string" + myint;

有什么帮助吗?

最佳答案

c中没有string类型,c字符串的定义是

  • '\0'nul 字节结尾的字节序列。

您可以这样使用snprintf()

#include <stdio.h>

int myint = 7;
char string[100] = "string";

snprintf(string, sizeof(string), "%d", myint);

这并不总是有效,但它适用于您当前的示例。

如果你不分配内存并用指针指向它,则不能将其与指针一起使用,可以通过这种方式实现

#include <stdlib.h> 
#include <stdio.h>

int myint;
char *string;

myint = 7;
string = malloc(100);

snprintf(string, 100, "mystring%d", myint);
/* when you are done using 'string', then */
free(string);

关于C:按 int 追加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28641656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com