Hey guys im just trying to make a simple program that will use structures to store your full name and age.
Code:
/********************************
Exercise 12271
Input and output your name, address and age to an appropriate structure.
©2005 Mark Crick
*********************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct person
{
char *firstName,*lastName;
long age;
};
void getInput(char *question, char *retVal)
{
int i;
printf(question);
fgets(retVal,BUFSIZ,stdin);
for(i = 0;i < BUFSIZ;i++, retVal++)
{
if(*retVal == '\n')
{
retVal++;
*retVal = '\0';
break;
}
}
}
int main()
{
char *input = malloc(BUFSIZ);
struct person user;
int length;
getInput("Please enter first Name ",input);
length = strlen(input);
user.firstName = malloc(length);
strncpy(user.firstName,input,length);
getInput("Please enter second Nname ",input);
length = strlen(input);
user.lastName = malloc(length);
strncpy(user.lastName,input,strlen(input));
getInput("Please enter age ",input);
user.age = strtol(input,NULL,10);
free(input);
printf("Name : %s , %s age : %i",user.firstName,user.lastName,user.age);
free(user.firstName);
free(user.lastName);
return 0;
}
Only problem is the output isnt correct, i was thinking that strlen doesnt count the terminating character so i tried length += sizeof(char) but they output was the same