gpt4 book ai didi

c - 陷入 fscanf 循环

转载 作者:行者123 更新时间:2023-11-30 14:20:28 27 4
gpt4 key购买 nike

该程序的要点是获取 2 个文件,一个是字典,另一个是文本,创建一个输出文件,并将文本文件中的所有单词放入其中,但将文本文件中不存在的单词大写字典。

当我运行程序时,它不断要求输入,所以看起来我陷入了 fscanf 循环。我只有 3 个 fscanf 循环。它一定是其中之一,但我不知道是哪一个以及为什么。

     #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>

#define wosi 20
int comp (const void *a, const void *b);

int main(int ac, char *av[])
{
int wordcount,i;
FILE *infi, *outfi;
char nothing, *dicptr, fina[100],letter[wosi];
unsigned char c;
/*to return error in case number of arguments mismatch*/
if (ac!=3)
{
fprintf (stderr," prog3: Man, I need 3 arguments to work!\n");
return (1);
}
/*first fscanf loop*/
while ((fscanf(infi,"%s",&nothing)!=0))
wordcount++;
/* end of step 2 */
dicptr = malloc(wordcount * wosi);
/* end of step 3*/

rewind(infi);
/*second fscanf loop */
for (i=0; fscanf(infi,"%s",&dicptr[i*wosi]) ;i++){}

/* this is qsort stage (finishing step 4) */

qsort (dicptr,wordcount,wosi,comp);

/*step 5 */
fclose (infi);
infi = fopen(av[2],"r");

if (infi == NULL )
{
perror( "opening" );
fprintf(stderr,"Can't open %s, the file is empty\n",av[2]);
return(1);
}
/*step 6 here */

strcpy(fina, av[2]);
strcat(fina, ".out");

outfi = fopen(fina, "w");

/*step 7*/
/* third fscanf loop */
while((fscanf(infi, "%s", letter)!= EOF));
{
for(i=0; letter[i]!='\0' ;i++)
{
c=letter[i];
letter[i]= toupper(c);
}

if(bsearch(letter,dicptr,wordcount,wosi,comp))
{
for(i=0;letter[i]!='\0';i++)
{
c=letter[i];
letter[i]= tolower(c);
}
}

/* fputs to print in out file*/
for(i=0; letter[i];i++)
{
fprintf(outfi,"%s",letter);
}
}
free(dicptr);
return (0);
}

int comp (const void *a, const void *b)
{
return (strcmp((const char *) a, (const char*) b));
}

最佳答案

这不是CodeReview.SE ,所以我只会给出一些提示。

首先,我敢打赌您没有使用 -Wall 编译器标志进行编译:

h2co3-macbook:~ h2co3$ clang -Wall -o baz baz.c
baz.c:24:14: warning: variable 'wordcount' is uninitialized when used here
[-Wuninitialized]
wordcount++;
^~~~~~~~~
baz.c:12:23: note: initialize the variable 'wordcount' to silence this warning
int wordcount,i;
^
= 0
baz.c:23:25: warning: variable 'infi' is uninitialized when used here
[-Wuninitialized]
while ((fscanf(infi,"%s",&nothing)!=0))
^~~~
baz.c:13:20: note: initialize the variable 'infi' to silence this warning
FILE *infi, *outfi;
^
= NULL
2 warnings generated.

第二,您的意思是使用 comp() 函数比较字符或字符串吗?如果是前者:

return *(const char *)a - *(const char *)b;

如果是后者:

return strcmp(*(const char **), *(const char **)b);

您似乎还存在一些语法错误,例如 while 循环条件后面的多余分号。

关于c - 陷入 fscanf 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15441894/

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