gpt4 book ai didi

c - 编写一个程序,读取输入文件并识别所有重复的单词

转载 作者:行者123 更新时间:2023-11-30 21:10:05 25 4
gpt4 key购买 nike

程序应首先打印重复单词的列表,然后打印唯一单词的列表。

我一直在尝试编写这个代码,但它仍然无法工作,它只打印一些独特的单词,请帮助我顺便说一句,这就是我到目前为止使用代码块所做的事情

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

int main()
{

FILE* inp;
char word[BUFSIZ],input[BUFSIZ][BUFSIZ],dup[BUFSIZ][BUFSIZ],unique[BUFSIZ][BUFSIZ];
int c=0,k=0,NumWord=0,n=0,found=0,m=1,g=0,j=0,h=0,b=1,d=1,a=0,size,detect=1,p=0;
char arr[BUFSIZ][BUFSIZ];

inp=fopen("u.txt","r") ;

if(inp==NULL){perror("Error in opening a file") ;return ;}
while(fscanf(inp,"%s",word)!=EOF)
{
strcpy(input[c++],word) ;
++NumWord;

}

size = NumWord - 1 ;

for( a=0 ; a < size ;a++)
{
//detect=1;
for( ; b < NumWord ; b++)
{
if(strcmp(input[a],input[b])==0 && detect==1)
{
strcpy(dup[a],input[a]) ;
++detect;
++h;
++found;
}
}

b = ++d;
if(!found)
{
strcpy(unique[n++],input[a]) ;
}
detect=1;
}

for( g = 0; g <h ; g++){
printf("%s ",dup[g]);

}
fclose(inp);

return (EXIT_SUCCESS);
}

最佳答案

您需要为 dupunique 缓冲区使用不同的索引

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

int main()
{
FILE* inp;
char word[BUFSIZ],input[BUFSIZ][BUFSIZ],dup[BUFSIZ][BUFSIZ],unique[BUFSIZ][BUFSIZ];
int c=0,k=0,NumWord=0,n=0,found=0,m=1,g=0,j=0,h=0,b=1,d=1,a=0,size,detect=1,p=0;
char arr[BUFSIZ][BUFSIZ];

int dup_idx =0;
int unique_idx =0;

inp=fopen("u.txt","r") ;

if(inp==NULL)
{
perror("Error in opening a file") ;return ;
}

while(fscanf(inp,"%s",word)!=EOF)
{
strcpy(input[c++],word) ;
++NumWord;

}

size = NumWord - 1 ;

for( a=0 ; a < size ;a++)
{
//detect=1;
for(b = 0; b < NumWord ; b++)
{
if(strcmp(input[a],input[b])==0 && detect==1)
{
strcpy(dup[dup_idx++],input[a]) ;
++detect;
++found;
}
}

b = ++d;
if(!found)
{
strcpy(unique[unique_idx++],input[a]) ;
}

detect=1;
}

printf("Dup: ");
for( g = 0; g < dup_idx ; g++){
printf("%s ",dup[g]);
}

printf("\nUnique: ");
for( g = 0; g < unique_idx ; g++){
printf("%s ",dup[g]);
}

printf("\n");

fclose(inp);

return (EXIT_SUCCESS);
}

关于c - 编写一个程序,读取输入文件并识别所有重复的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32348883/

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