gpt4 book ai didi

c - 在 'C' : How to clear the char array for the next string 中编程

转载 作者:行者123 更新时间:2023-11-30 20:34:41 25 4
gpt4 key购买 nike

我尝试编写一个可以按特定顺序读取文本文件的代码。问题是字符串覆盖了数组中的最后一个字符串,但我希望为下一个字符串清除数组,但我不知道该怎么做。

这是文本文件:

@str_hello_world_test={hello world!test}
@str_hello_world={hello world}

输出在这里:

symbol:str_hello_world_test²`
string:hello world!testtest²`

hello world!testtest²`
symbol:str_hello_worldttest²`
string:hello worldorldttest²`

hello worldorldttest²`

我的代码:

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

#define MAXBUF 255

//prototypes
void readingFile(FILE* fp);
char* readingSymbol(FILE* fp);
char* readingString(FILE* fp);

int main(void)
{
FILE* fp;
char directory[MAXBUF];

puts("Geben sie ein Verzeichnis ein: ");
gets(directory);
fp = fopen(directory, "r");

readingFile(fp);

system("pause");
return EXIT_SUCCESS;

}

void readingFile(FILE* fp){
int c;

while((c = fgetc(fp)) != EOF){
char* symbol = readingSymbol(fp);
char* string = readingString(fp);
printf("%s\n", symbol);
}
return;
}

char* readingSymbol(FILE* fp){
int c;
int i = 0;
char symbol[MAXBUF];

while((c = fgetc(fp)) != '='){
if(c == '@'){
continue;
}
else{
symbol[i] = (char)c;
i++;
}
}
printf("symbol:%s\n", symbol);
return symbol;
}

char* readingString(FILE* fp){
int c;
int i = 0;
char str[MAXBUF];

while((c = fgetc(fp)) != '}'){
if(c == '='){
continue;
}
else if(c == '{'){
continue;
}
else{
str[i] = (char)c;
i++;
}
}
printf("string:%s\n\n", str);
return str;
}

最佳答案

您的代码有一个明显的未定义行为示例。您返回悬空引用。将警告级别调得尽可能高。然后注意这些警告。对于为什么会发生这种情况,一个粗略的(依赖于实现的)合理解释是,这两个函数具有完全相同的堆栈帧布局。因此,当您调用第二个字符串时,它会用另一个字符串填充完全相同的位置。

立即修复是避免返回指向缓冲区的指针,并将指向缓冲区的指针传递到函数中。然后它负责填充它:

char symbol[MAXBUF];
readingSymbol(fp, MAXBUF, symbol);

// ...

void readingSymbol(FILE* fp, size_t const buff_len, char symbol[buff_len]) {
int c;
int i = 0;

while((c = fgetc(fp)) != '='){
if(c == '@'){
continue;
}
else{
symbol[i] = (char)c;
i++;
}
}
printf("symbol:%s\n", symbol);
}

以上是有效的 C99。如果您由于某种原因在 C89 中进行编译,或者您的编译器不支持变长数组,请将函数签名更改为如下:

void readingSymbol(FILE* fp, size_t const buff_len, char *symbol)

关于c - 在 'C' : How to clear the char array for the next string 中编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41789857/

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