0

I have a text file and the lines of text are divided by three strings. How can I print just the second word?

I've tried to print after the blank space (" "), but is not working as supossed to.

The next code prints the first word of each line:

void leerEmpleados(){
    FILE *fp;
    struct empleados{
        char codigo[6];
        char nombre[20];
        char apellido[20];
        char departamento[20];
    };

    struct empleados emp;

    fp = fopen("Empleado.txt", "r");
    if (fp == NULL) {
        printf("El archivo no existe");
    } else {
        //Lee los códigos
        while (!feof(fp)) {
            fscanf(fp,"%s%*[^\n]",emp.codigo);
            printf("%s\n",emp.codigo);
        }

    }
    fclose(fp);
}

The file data can contain something like this: 102 John Musician'\n' 103 Paul Musician'\n' 104 Ringo Musician

1 Answers1

0

Change your format string to " %*s%s%*[^\n]". %*s reads the first word on the line and discards it, then %s reads the second word.

Barmar
  • 741,623
  • 53
  • 500
  • 612