How to print only once the name repeated?

Asked

Viewed 71 times

2

For one or two names repeated, it works well, but if I make them all the same he repeats them ten times. I’ve tried using flag, but I can’t 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;
}
  • You can create another variable that stores repeated names, then just enter there if it doesn’t exist, then just print

  • 1

    Set "repeated". If there are two equal ones in the whole list is already repeated? Or only when it appears for the second time is repeated?

  • If there are two equal ones in the list it is already repeated. I am trying to understand correctly comparison of strings to use in a name validation. For example, if there is already a name in the list, it asks the user to type the name again.

  • 1

    @Lucascorrhea Can use my implementation, only instead of using nomes_repetidos asks again for a different name

1 answer

2


An alternative to solve this problem is to create a new variable nomes_repetidos in which it stores the repeated names, if it does not yet exist, for this it takes a function that searches in the vector whether it exists or not.


Using static memory as it has 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 code snippet below what you do is:

  1. See if it’s a word repeated
  2. If it is repeated and does not exist on nomes_repetidos adds
  3. 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]);

FULL CODE ON IDEONE

Browser other questions tagged

You are not signed in. Login or sign up in order to post.