While finds no match, C language

Asked

Viewed 98 times

0

I have the following code in 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;
}

However, when using the function seacrPlayList(), and type the name of the song, identify the inserted one, the system returns me saying that nothing was found.

Note: When there is no music in the playlist, it works correctly.

Can someone help me with this problem? I tested the following code on the website Repl.it

To be able to test, you must insert a song, singer and time for first, option 1.

  • 2

    The operator ==, in this case, it will compare the memory region. Have you seen the strcmp? There are several questions here at Sopt on the subject

  • 1

    Possible duplicate of Compare a char vector?

  • I created the following variable: int ret = strcmp(busc, aux->music);, and I test it, however, returns me the value of -10

  • 1

    The strcmp returns 0 when the two strings are equal, a negative value when the first string is less than the second and a positive value otherwise. The value returned (when different from 0) indicates which character the function encountered divergence in. So, -10 indicates that the position character 10 of busc is less than the position character 10 of aux->music and that all previous characters were equal. Reference strcmp here.

  • I modified my code, as explained. I will test agr no if if (strcmp(busc,aux->music)==0){, but the error persists. I’ve even put a printf of the two to see if it matches the values of both, printf("%s", busc); and printf("%s", aux->music);, still returns me -10

1 answer

1


The problem is that the fgets() stores the \n at the end of string, while in the case of scanf() the \n stays in the buffer. So when the strcmp() will compare the strings he finds: musica1\n and musica1.

To avoid this, do the following in your music inclusion function:

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;
  }
}

Browser other questions tagged

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