-2
Well, I did this vector test, but I’m having a problem with the bool type, which never turns false and displays the message of not found.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main() {
char *palavras[] = {"maca", "uva", "pera"};
int tamanho = sizeof(palavras) / sizeof(char *);
int tam = tamanho;
char nome[100];
bool achou = false;
while(true) {
if(tam > 0) {
printf("[ ");
for(int i=0; i<tam - 1; i++) {
printf("%s, ", palavras[i]);
}
printf("%s ]\n", palavras[tam - 1]);
}
printf("Deseja excluir qual fruta? ");
fgets(nome, 20, stdin);
nome[strlen(nome) - 1] = '\0';
if(tam == 0) { puts("Sem frutas disponiveis"); break; }
for(int i=0; i<tam; i++) {
achou = false;
if(!strcmp(nome, palavras[i])) {
printf("Fruta: %s, excluida.\n\n", nome);
for(int j=i; j<tam - 1; j++) {
palavras[j] = palavras[j + 1];
}
tam--;
achou = true;
break;
}
if(achou) { //se falso
printf("Fruta: %s, nao encontrada.\n\n", nome);
} } }
return 0;
}
I can’t figure it out.
Why you remove the last letter of the name of the fruit you enter, in line 24?
– Wtrmute
Are you referring to fgets?
– Joao
The line immediately below the
fgets()
– Wtrmute
name[strlen(name) - 1] = ' 0'; but this will remove the ' n', without it the comparison would not work.
– Joao
You are right; it is the
gets()
that did not inculcate the return car in the string that returns. I compiled your code here and it worked correctly, however. There seems to be no error in it.– Wtrmute
if (achou) { // se falso
shouldn’t beif (!achou) { // se falso
? And maybe you should be out for that if.– lemoce