1

Im trying to compare 2 strings with strcmp(). One of them is implemented by keyboard, but the other is scanned from a file, so i use fgets(vec[i].nombre,80,fentrada); where "vec" is a vector from a typedef struct, with a char variable named "nombre". The thing is although I enter the exact same string which is taken from the file, it doesnt return a 0. I limited the maximum characters to the length of the string which is in the file, and it makes it work, so must have something to do with the blank spaces. But the point is making it work for whatever the length of the string is.

This is the structure:

typedef struct f{
    int dia;
    int mes;
    int anno;
    };
typedef struct pelicula{
    char nombre[80];
    float nota;
    f fecha;
}peliculas;
peliculas vec[dim];

Here's the sentence to scan what is in the file.

FILE *fentrada=fopen("peliculas.dat","rt");
while(!feof(fentrada)){
    fgets(vec[i].nombre,80,fentrada);
    fscanf(fentrada,"%i",&vec[i].fecha.dia);
    fscanf(fentrada,"%i",&vec[i].fecha.mes);
    fscanf(fentrada,"%i",&vec[i].fecha.anno);
    fscanf(fentrada,"%f\n",&vec[i].nota);
    i++;
    printf("\n");
}

And this is where i compare the strings:

int i=0,j=0;
char *nombre,cos[46],c[66];
strcpy(c,vec[i].nombre);
gets(cos);
printf("%s\n",c);
printf("%i",strcmp(cos,c));

And this is what the file looks like:

Casa Blanca
4 11 2013
6
Mi villano favorito
5 11 2013
7
Crepusculo
6 11 2013
8

P.D, ive tried using scanf(%s) instead of fgets but it scans just "Casa", then "Blanca", so i get 6 elements instead of 3...

7

1 Answer 1

0

Possible Problems:

lines you read from file using fgets contains a new line character but gets doesn't. also using feof(file) is not advisable

Solution:

use fscanf instead of fgets. It returns a integer value which represents how many values are matched with the file input.

fscanf returns the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

Code:

just change in the code for scanning the file lines

int ret;
while(ret = fscanf(fentrada,"%[0-9a-zA-Z ] %d %d %d %d ", vec[i].nombre, &vec[i].fecha.dia, &vec[i].fecha.mes, &vec[i].fecha.anno, &vec[i].nota))
{
    if(ret == EOF)
    {
        break;
    }else
    {
        // printf("\n %d",ret);
        // ^ prints how many values are successfully matched
    }
}

note: I have checked this code for your input. It works fine and returns 0 as the output of strcmp

reference: fscanf - TutorialsPoint

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.