I'm trying to compare the initials of some names previously obtained from a text file, the format of the file would be this:
nombre dato1 dato2
nombre dato1 dato2
nombre dato1 dato2
nombre dato1 dato2
I ask the user to type the name of the file and if it is correct I ask you to type a letter, which will be the initial one to compare, then I start to read the data of the file and I must know how many names begin with the letter indicated by the user.
The code would be something like this:
#include <stdio.h>
int main() {
FILE *archivo = NULL;
char fichero[80];
char nombre[15];
char inicial[5];
int i, j, dato1, dato2;
printf ("Teclea el nombre del archivo: ");
scanf ("%s", fichero);
archivo = fopen (fichero, "r");
if (!archivo) {
printf ("Error: no se pudo abrir el fichero: %s\n", fichero);
return 1;
}
printf("Teclea una inicial: ");
scanf("%s", &inicial);
for (i=0; fscanf(archivo, "%s %d %d", nombre, &dato1, &dato2) == 3; i++) {
printf("%s %d %d\n", nombre, dato1, dato2);
if (nombre[0]==inicial[0]) {
j++;
}
}
printf("Hay %d nombres que empiezan por la inicial %c \n", j, inicial[0]);
fclose (archivo);
return 0;
}
I know that c you can not compare characters directly, but I tried with strcmp
and it did not work either. What would be the correct way to know how many names begin with the initial?
Thanks for the help.