gpt4 book ai didi

C语言-使用fgets的奇怪输出

转载 作者:行者123 更新时间:2023-11-30 17:43:04 26 4
gpt4 key购买 nike

这是有问题的代码:

FILE *fp;
char str[256];
/* opening file for reading */
fp = fopen("file.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
while( fgets (str, sizeof(str), fp)) {
int i;
char *temp;
temp=malloc(257);
for(i=0;i<sizeof(str)-1;i++){
if(isalpha(str[i])){
append(temp,str[i]);
}else{
printf(" %s ",temp);
temp=calloc(257,sizeof(char));
}
}
}

如果文本文件如下:

"Here's a text
file example. No
idea what's wrong."

然后它将输出以下内容:

"Here s a text          vf       file example No               vf               idea what s wrong".

所需的引用输出:

"Here s a text file example No idea what s wrong"

基本上每次涉及换行时都会出现一些奇怪的东西。当我运行它时可能是“vf”。下次可能是“ZG”。每次我运行程序时它都会改变。

最佳答案

读取 buf 未由 fgets()` 填充的部分。

替换

// for(i=0;i<sizeof(str)-1;i++)
for(i=0;i<strlen(str);i++)

或更好

// for(i=0;i<sizeof(str)-1;i++)
size_t len = strlen(str);
// removed potenital ending '\n'
if ((len > 0) && (str[len-1] == '\n')) len--;
size_t i;
for (i = 0; i < len; i++)

关于C语言-使用fgets的奇怪输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20317832/

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