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

标签 c

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

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

#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/

相关文章:

c++ - C , C++ 非同步线程返回一个奇怪的结果

c - 如何从 C 中的字符串中删除重音符号?

c - 将 nC3 分配给整型变量时,哪个选项是正确的?

c++ - 将三位值存储到 unsigned char 数组

c - 为什么 Doxygen 没有记录在 C 函数中定义的宏?

c++ - 将较小的数组复制到较大的数组中

c - Reinterpret_cast/C 中带有 union 的类型双关功能

c - 简单红黑树中的段错误

c - 为什么我能够将 char* 值分配给字符串?

c - 需要帮助转换 C Mersenne twister 实现以对我有用