How to print the repeated name only once?

2

For one or two repeated names, it works fine, but if I make them all the same it repeats about ten times. I already tried to use flag, but I can not understand the reasoning.

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

/* 
Lucas Correia, 2018

 */

int main(int argc, char *argv[]) {
    char nomes[5][50];
    int i=0, j=0, flag = 0;

    for(i=0; i < 5; i++){
        printf("Informe o nome:");
        scanf(" %[^\n]s", nomes[i]);
    }


    for(i=0; i < 5; i++){
        for(j = i+ 1; j < 5; j++){
            if(stricmp(nomes[i], nomes[j])==0){
                printf("\nRepetead: %s", nomes[i]);
                flag = 1;
                if(!flag){
                    break;
                }
            }
        }
    }

    return 0;
}
    
asked by anonymous 03.09.2018 / 15:58

1 answer

2

An alternative to solve this problem is to create a new variable nomes_repetidos where it stores the repeated names, if it does not already exist , for this you need a function that looks in the vector whether it exists or not .

Using static memory as you have been using:

/** 1 caso encontre | -1 caso não encontre **/
int procura(char nome[][50], int n, char nome_rep[50])
{
    int i;
    for(i=0; i<n; i++)
    {
        if(!strcmp(nome[i],nome_rep))
            return 1;
    }
    return -1;
}

In this excerpt of code below what it does is:

  • See if it is a repeated word
  • If it is repeated and does not exist in nomes_repetidos add
  • Increases the size of nomes_repetidos
  •  if(strcmp(nomes[i], nomes[j])==0)  /** 1. **/
        {
           if(procura(nomes_repetidos, tamanho, nomes[i])==-1)  /** 2. **/
           {
               strcpy(nomes_repetidos[tamanho], nomes[i]); /** 2. **/
               tamanho++;  /** 3. **/
           }
        }
    

    After that, just print your data normally:

    for(i=0; i<tamanho; i++ )
            printf("\nRepetead: %s", nomes_repetidos[i]);
    

    IDEONE COMPLETE CODE

        
    03.09.2018 / 16:36