0

Tenho o seguinte código em C:

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

struct crPlayList{
    char music[120], singer[120];
    float mustime;
    struct crPlayList *next;
};

struct crPlayList *start, *end, *aux;

void inscrPlayList(){
    int c;

    struct crPlayList *new = (struct crPlayList *)malloc(sizeof(struct crPlayList));
    printf("\nDigite o nome da música:");
    fgets(new->music, 39, stdin);
    printf("Digite o nome do cantor:");
    fgets(new->singer, 39, stdin);
    printf("Digite o tempo de duração da música:");
    scanf("%f", &new->mustime);

    while ((c = getchar()) != '\n' && c != EOF) {} // Limpar buffer do teclado

    new->next = NULL;
    if (start == NULL){//A Fila esta vazia e iremos inserir o primeiro elemento
        start = end = new;
    printf("\nMúsica inserida com sucesso!!\n\n");
    }else{
        end->next = new;
        end = new;
    }
}

void delcrPlayList(){

    char ch;

    if (start == NULL){
        printf("\nPlaylist vazia!\n\n");
    }else{
        printf("\nTem certeza que deseja limpar toda a playlist? S/N :");
        ch = getchar();
        if (ch == 's' || ch == 'S'){
            while (start != NULL){
                aux = start;
                start = start->next;
                free(aux); // Libera o espaco na memoria
            }
          printf("\nOperação executada com sucesso!\n\n");
        }else{
          printf("\nNão foi possível concluir a operação!\n\n");
        }
    }
}

void listcrPlayList(){
    aux = start;
    if (start == NULL){
        printf("\nNenhuma música encontrada!");
    }else{
        while (aux != NULL){
            printf("\nMúsica: %s", aux->music);
            printf("Cantor: %s", aux->singer);
            printf("Duração: %f\n", aux->mustime);
            aux = aux->next;
        }
    }

    printf("\n\n");
}

void seacrPlayList(){
    aux = start;

    if (start == NULL){
        printf("\nPlaylist vazia!");
    }else{
        char busc[120];
        printf("\nDigite o nome da música:");
        scanf("%s", busc);

    while (aux != NULL){
            if (busc == aux->music){
                printf("\nMúsica  %s encontrada:\n\n", aux->music);
                printf("Música: %s", aux->music);
                printf("Cantor: %s\n\n", aux->singer);
        printf("Duração: %f\n\n", aux->mustime);
                return;
            }else{
                aux = aux->next;
            }
        }

        if (aux == NULL){
          printf("\nMúsica  %s não encontrada!\n", busc);
        }
    }

    printf("\n\n");
}

int main(){
    setlocale(LC_ALL, "");

    int opt, c;

    do{
        printf("* ------------------------------------ *\n");
        printf("| 1 - Adicionar música                 |\n");
        printf("| 2 - Buscar música                    |\n");
        printf("| 3 - Listar músicas                   |\n");
        printf("| 4 - Limpar playlist                  |\n");
        printf("| 5 - Sair                             |\n");
        printf("| Digite a opção desejada:");

        scanf("%d", &opt);
        while ((c = getchar()) != '\n' && c != EOF) {} // Limpar buffer

        switch (opt){
            case 1:
                inscrPlayList();
                system("pause");
                break;
            case 2:
                seacrPlayList();
                system("pause");
                break;
            case 3:
                listcrPlayList();
                system("pause");
                break;
            case 4:
                delcrPlayList();
                system("pause");
                break;
            case 5:
                printf("\nFim. Obrigado por usar o sistema!\n\n");
                system("pause");
                break;
            default:
                printf("\nEscolha Invalida!!\n\n");
                system("pause");
                break;
        }
        system("cls");
    }while (opt != 5);

    return 0;
}

Porém, ao usar a função seacrPlayList(), e digitar o nome da música, identica a uma inserida, o sistema me retorna dizendo que nada foi encontrado.

Observação: Quando não há música alguma na playlist, ele funciona corretamente.

Alguém pode me ajudar nesse problema? Testei o seguinte código no site Repl.it

Para conseguir testar, deve inserir uma música, cantor e tempo por primeiro, opção 1.

5
  • 2
    O operador ==, nesse caso, vai comparar a região de memória. Você já viu a strcmp? Tem diversas questões aqui no SOpt sobre o assunto 3/05/2019 às 22:53
  • 1
    Possível duplicata de Comparar um vetor do tipo char? 3/05/2019 às 22:56
  • Criei a seguinte variável: int ret = strcmp(busc, aux->music);, e passo a testa-la, porém, me retorna o valor de -10 4/05/2019 às 0:07
  • 1
    O strcmp retorna 0 quando as duas strings são iguais, um valor negativo quando a primeira string é menor que a segunda e um valor positivo caso contrário. O valor retornado (quando diferente de 0) indica em qual caractere a função encontrou divergência. Sendo assim, -10 indica que o caractere da posição 10 de busc é menor que o caractere da posição 10 da aux->music e que todos os caracteres anteriores eram iguais. Referência do strcmp aqui. 4/05/2019 às 0:39
  • Modifiquei meu código, conforme o explicado. Passo a testar agr no if if (strcmp(busc,aux->music)==0){, mas persiste o erro. Até já coloquei um printf dos dois para ver se não bate os valores de ambos, printf("%s", busc); e printf("%s", aux->music);, ainda me retorna -10 4/05/2019 às 15:13

1 Resposta 1

1

O problema é que o fgets() armazena o \n no final da string, enquanto no caso do scanf() o \n fica no buffer. Então quando o strcmp() vai comparar as strings ele encontra: musica1\n e musica1.

Pra evitar isso, faça o seguinte na sua função de inclusão de musica:

void inscrPlayList(){
  int c;

  struct crPlayList *new = (struct crPlayList *)malloc(sizeof(struct crPlayList));
  printf("\nDigite o nome da música:");
  fgets(new->music, 39, stdin);
  //removendo o \n da string após o fgets
  new->music[strcspn(new->music, "\n")] = 0;
  printf("Digite o nome do cantor:");
  fgets(new->singer, 39, stdin);
  printf("Digite o tempo de duração da música:");
  scanf("%f", &new->mustime);

  while ((c = getchar()) != '\n' && c != EOF) {} // Limpar buffer do teclado

  new->next = NULL;
  if (start == NULL){//A Fila esta vazia e iremos inserir o primeiro elemento
      start = end = new;
  printf("\nMúsica inserida com sucesso!!\n\n");
  }else{
      end->next = new;
      end = new;
  }
}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .