程序应首先打印重复单词列表,然后打印唯一单词列表。
我一直在尝试编码,但它仍然无法工作它只打印一些独特的单词请帮助我 这是我到目前为止所使用的代码块
#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);
}
答案 0 :(得分:0)
您需要dup
和unique
缓冲区
#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);
}
答案 1 :(得分:0)
首先,您需要初始化字符串缓冲区dup
和unique
。这可能不是您的问题的原因,但如果您不这样做,则在您打印dup
时,您的程序会有未定义的行为。
memset(dup, 0, sizeof dup);
memset(dup, 0, sizeof unique);
其次,我不明白你分配b
的方式。一个简单的开始是删除行b = ++d;
并在b
循环中分配for
:
for(b = a + 1; b < NumWord ; b++)
查看数组的其余部分就足够了,因为如果一个单词在自身之前有重复,那么在处理该前一个单词时就会检测到它。