-
Fairly simple problem
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
-
http://faq.cprogramming.com/cgi-bin/...&id=1043284385
http://www.daniweb.com/code/snippet278.html
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
{
char *firstName,*lastName;
int age;
};
void getInput(const char *question, char *retVal)
{
fputs(question, stdout);
fflush(stdout);
if ( fgets(retVal, BUFSIZ, stdin) != NULL )
{
char *newline = strchr(retVal, '\n');
if ( newline != NULL )
{
*newline = '\0';
}
}
}
int main()
{
char input[BUFSIZ];
struct person user;
size_t length;
getInput("Please enter first Name ", input);
length = strlen(input);
user.firstName = malloc(length + 1);
if ( user.firstName != NULL )
{
strcpy(user.firstName, input);
}
getInput("Please enter second Name ", input);
length = strlen(input);
user.lastName = malloc(length + 1);
if ( user.lastName != NULL )
{
strcpy(user.lastName, input);
}
getInput("Please enter age ", input);
user.age = strtol(input, NULL, 10);
printf("Name: %s, %s age:%i\n", user.firstName, user.lastName, user.age);
free(user.firstName);
free(user.lastName);
return 0;
}