Get names of a text file and compare your initials

1

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 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.

    
asked by Newbie_overflow 12.12.2018 в 17:05
source

1 answer

0

Some things about your program, initial is the name of an array, so it is already a pointer, the correct thing is

scanf("%s", inicial);

Second, the comparison of characters with == will work well, we are really going to compare whole numbers. Last and most important, it is most likely that the for loop will not run, everything will depend on the organization of the file from which it reads, without seeing the file it is impossible to help. For example if we have a file names.txt organized in the following way:

Angel
Roberto
Raul
Miguel
Manuel
Manolo
Mercedes

Then a loop like the following should work:

for (i=0; fscanf(archivo, "%s", nombre) == 1; i++)
    
answered by 12.12.2018 в 21:12