如何在字符串中添加/追加字符



我是C编程的新手,正在尝试使用strcat将字符附加到字符串中。我尝试使用这个问题中讨论的内容:如何在C中向char数组添加char/int?,但它不起作用。我一直得到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);
}

您可能想要这样的东西:

#include <stdio.h>
#include <string.h>
char box[100] = "";
int main()
{
FILE* fp = fopen("somefilename", "r");
int c;
for (c = getc(fp); c != EOF; c = getc(fp)) {    
char tempC[2];
tempC[0] = c;
tempC[1] = 0;
strncat(box, tempC, 1);
}
}

这编译了,但它是可怕的代码:

  • 不检查fopen是否成功
  • 在这里使用strncat是非常低效的。作为练习,在不使用strncat或其他str...函数的情况下更改此项
  • 无需使用全局变量

最新更新