gpt4 book ai didi

将 int 连接到 char[]

转载 作者:太空宇宙 更新时间:2023-11-04 01:04:44 25 4
gpt4 key购买 nike

我是 C 的新手(很明显),我收到以下错误:

警告:传递“strncat”的参数 2 使指针来自整数而不进行强制转换 [默认启用]

代码如下:

int main(void)
{
FILE *fp;
int c;
unsigned char file[1024] = "/path/to/file";
unsigned char text[1024] = "SomeText";

fp = fopen(file, "r");
if (fp == NULL)
{
perror("Error opening file");
return(-1);
}

while ((c = fgetc(fp)) != EOF && c != '\n')
{
strncat(text,c,1);
}
}

显然这对我有意义,但不幸的是编译器不是。我怎样才能写得更好?

最佳答案

strncat 无法将字符附加到字符串,因为它将字符串附加到字符串。您可以从 c 字符创建一个单字符的字符串,但是使用 strcat 是一种矫枉过正:您最好创建一个指针,然后通过向其添加字符来追加:

char *p = &text[strlen(text)]; // Start appending at the last position of text
while ((c = fgetc(fp)) != EOF && c != '\n') {
*p++ = c;
if (p == &text[1023]) break;
}
*p = '\0';

已添加循环中的指针检查以处理缓冲区溢出。

关于将 int 连接到 char[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227740/

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