I have a problem with my C code, hope you can help me. The program is about making a basic book "database". When I run the following code (in Xcode), I don't know why the following sentence gets skipped:
gets(nombre[i]);
On the terminal it directly prints the following if I take option 1 from the menu:
Bienvenido al catalogo de libros.
Catalogo de tarjetas: 1. Introducir 2. Buscar por autor 3. Buscar por titulo 4. Salir
Elija opcion:1 warning: this program uses gets(), which is unsafe.
Introduzca el nombre del libro:Introduzca el autor del libro:
Ok, so i've tested my scanf("%d", &opcion); using a printf("%d", opcion); right after to proove that scanf reads correctly my input. Surprisingly, it reads the option I introduce correctly. Moreover, i've tried running the program with no "\n" in any part to see if gets(nombre[i]) works but still it gets jumped...
Any ideas?
This is the full code (not long):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#define MAX 100
char nombre[MAX][20];
char autor[MAX][20];
char edit[MAX][20];
char buscar[20];
char buscar_t[20];
char buscar_a[20];
int opcion,i,j,k,l;
void menu(void);
void intro(void);
void buscar_autor(void);
void buscar_tit(void);
void salir(void);
void main(void)
{
printf("Bienvenido al catalogo de libros. \n");
menu();
}
void menu(void)
{
printf("\n Catalogo de tarjetas:");
printf("\n 1. Introducir");
printf("\n 2. Buscar por autor");
printf("\n 3. Buscar por titulo");
printf("\n 4. Salir");
printf("\n Elija opcion:");
scanf("%d", &opcion);
switch (opcion) {
case 1:
intro();
break;
case 2:
buscar_autor();
break;
case 3:
buscar_tit();
break;
case 4:
salir();
break;
}
}
void intro(void)
{
for (i=0; i<MAX; i++)
{
printf("Introduzca el nombre del libro:");
gets(nombre[i]);
if (!strcmp(nombre[i],"salir"))
{
break;
}
printf("Introduzca el autor del libro:");
gets(autor[i]);
printf("Introduzca la editorial del libro:");
gets(edit[i]);
}
menu();
}
void buscar_tit(void)
{
printf("Introduzca el titulo del libro que quiera buscar:");
gets(buscar_t);
for (j=0; j<MAX+1; j++)
{
if (!strcmp(nombre[j],buscar_t))
{
printf("El libro se ha encontrado, el titulo es %s. ", nombre[j]);
break;
}
if (j=MAX)
{
printf("El libro no se ha encontrado.");
break;
}
}
}
void buscar_autor(void)
{
printf("Introduzca el autor del libro que quiera buscar:");
gets(buscar_a);
for (k=0; k<MAX+1; k++)
{
if (!strcmp(autor[k],buscar_a))
{
printf("El libro se ha encontrado, el titulo es %s. ", nombre[k]);
break;
}
if (k=MAX)
{
printf("El autor no se ha encontrado.");
break;
}
}
}
void salir(void)
{
printf("Muchisimas gracias por usar el catalogo de libros. \n");
}
Hope you can help me figure out the error.
Thanks guys.