Does not my file save an entire value in C ++?

0

My program consists in creating a file .dat , with 3 values (name, age and country), read the file and show its contents.

The problem I have is that when I open my file, it only saves me the char values. I think the error is in getchar(); , but if I do not use it, it will not let me enter the country.

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <conio.h>

using namespace std;

struct Persona
    {
        char nombre[40];
        int edad;
        char pais[30];
    }est;

int main()
{
    FILE* matatero;
    matatero=fopen("agenda.dat","a+");
       puts("Ingrese el nombre: ");
       gets(est.nombre);
       fprintf(matatero,"%s",est.nombre);
       puts("Ingrese edad: ");
       scanf("%d",&est.edad);
       fscanf(matatero,"%d",&est.edad);
       getchar();
       puts("Ingrese pais: ");
       gets(est.pais);
       fputs(est.pais,matatero);
    fclose(matatero);

    matatero=fopen("agenda.dat","r");
    while(!feof(matatero))
    {
        fgets(est.nombre,40,matatero);
        puts(est.nombre);
        fscanf(matatero,"%d",&est.edad);
        printf("%d",est.edad);
        fgets(est.pais,30,matatero);
        puts(est.pais);
        cout<<endl;
    }
    fclose(matatero);

    return 0;
}

Thank you.

    
asked by José T. 20.02.2017 в 16:39
source

1 answer

1
puts("Ingrese el nombre: ");
gets(est.nombre);
fprintf(matatero,"%s",est.nombre);

You ask for a name, you read it and you store the value in the file ...

puts("Ingrese edad: ");
scanf("%d",&est.edad);
fscanf(matatero,"%d",&est.edad);

You ask for age, you recover it ... and you overwrite the value with whatever you want in the file ... it does not sound good. Replace fscanf with fprintf

    
answered by 20.02.2017 / 16:43
source