问题描述
我想遍历一个文本文件并连接所有字符串,直到遇到空行,然后对下一个字符串执行相同操作,依此类推。每个字符串连接的结果应该添加到一个 char* 数组中:
char* element_arr[287];
void splitPassports(FILE* file_to_read){
char element[500];
char str[80];
int i = 0;
int j = 0;
while(j < FILELENGTH){
if (fgets(str,80,file_to_read) && !isBlank(str)){
strcat(element,str);
printf("The string is: %s\n",str);
}else if (isBlank(str)){
element_arr[i] = element;
memset(element,'\0',sizeof element);
printf("%s\n",element_arr[0]);
i++;
}
j++;
}
fclose(file_to_read);
}
但是,当我尝试这样做时,我收到了非法硬件指令错误(我使用的是 Mac)。如何将新字符串正确添加到现有字符串中,然后将其附加到我的数组中,然后将其设置回零以对几行执行相同操作,直到遇到空行? 我对 C 比较陌生,所以提前致谢:)
解决方法
-
char element[] = "";
您声明了 1 个字符长的数组,因此strcat
将始终失败(除非第二个字符串也是空的)。 即使你以正确的方式定义它,赋值
element_arr[i] = element;
你每次都会给数组元素分配相同的引用,所以数组会简单地填充对同一个对象的引用。-
while(!feof(file_to_read))
- 读取 Why is “while ( !feof (file) )” always wrong?
我建议从 C 书开始,因为您不了解该语言的基础知识。