Hello
I cant get the use of fgets and sscanf when it comes to fetching an integer. It works well with a string. I could typecast it but I am not coming on either. Or what is the safe way of fetching integer input? I dont want scanf, it aint safe. I just imagined something like fgetint or fgetlong should exist, and it seems it does, because I put it and the compiler didn't complain.
Well this is a very simple code. 2 structures, one inside the other. It is about storing the name, the telephone and the birthdate of a user. The birthdate is broken into day, month and year, so it makes part of a separate structure. Then, i get the name of this separate structure and put it inside the other one, just as as any other member.
well her is the code, but I get lots of problems when trying to read that, starting with sscanf after the fgetlong. It says passing of argument 1, and 2 and 3 of strtol makes pointer from integer without a cast.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct birthdate{
int day;
int month;
int year;
}birthdate_t;
typedef struct contacto {
char name[30];
long telephone;
birthdate_t bd; // es decir, bd es de tipo struct
} contacto_t;
contacto_t create_contact(void);
contacto_t create_contact(){ // it returns a structure type
contacto_t c1; // creates actually a blank structure y and here below I just input the data for storage
printf("Enter name: ");
fgets(c1.name, sizeof(c1.name), stdin);
sscanf(c1.name, "%s", &c1.name);
printf("Enter telephone: ");
fgetlong(c1.telephone, sizeof(c1.telephone), stdin);
sscanf(strtol(c1.telephone, "%d", &c1.telephone));
printf("Enter birthdate");
c1.bd = create_birthdate();
}
birthdate_t create_birthdate(){
birthdate_t bd1;
Printf("Enter day: ");
fgets(bd1.day, sizeof(bd1.day), stdin);
sscanf(bd1.day, "%d\n", &bd1.day);
Printf("Enter month: ");
fgets(bd1.month, sizeof(bd1.month), stdin);
sscanf(bd1.month, "%d\n", &bd1.month);
Printf("Enter year: ");
fgets(bd1.year, sizeof(bd1.year), stdin);
sscanf(bd1.year, "%d\n", &bd1.year);
return bd1;
}
main (void)
{
create_contact();
}