【发布时间】:2023-03-13 15:34:01
【问题描述】:
我是 C 编程新手,我正在尝试使用 strcat 将字符附加到字符串。我尝试使用这个问题中讨论的内容:How to add a char/int to an char array in C?,但它不起作用。我不断收到error: invalid initializer char characStr[2] = c;。不知道我做错了什么。
谢谢,
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char box[100] = "";
fp = fopen(filename, "r");
for (c = getc(fp); c != EOF; c = getc(fp)){
char tempC[2] = c;
strncat(box,tempC,1);
}
【问题讨论】:
-
在此设置中,您可以保持字符串的长度,只需在循环中和循环后执行
box[current_length++] = c;:box[current_length] = '\0';- 但请确保current_length永远不会超过 99将其用作索引。 -
请完整代码?
-
尝试:
char tempC[2] = { c, 0 };然后您可以简单地使用strcat(box, tempC)(尽管缺少边界检查)。 -
strcat()是那些几乎不需要使用的函数之一。为了安全地调用它,您需要知道目标字符串的当前长度、底层数组的长度以及要添加的字符串的长度,这样您就可以避免缓冲区溢出。鉴于这些数字,您可以使用memcpy()或strcpy()代替,因为strcat()必须再次找到目的地的长度,即使您已经知道它。
标签: c