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.