Reputation: 1
#include <stdio.h>
#include <stdlib.h>
int main()
{
int _age;//declare variable
getAge();//calls function
welcomeMessage();//calls function
return 0;
}
int getAge(int _age)//takes input from user and assigns a value to age
{
printf("What is your age?\n");
scanf("%d", &_age);
}
int welcomeMessage(int _age)//prints how old you are
{
printf("Welcome, you are %d years old.\n", _age);
}
I keep getting a random number for the age and I need to recognize what I put in for scanf
Upvotes: 0
Views: 102
Reputation: 681
Your int getAge(int _age)
function should be like the following:
void getAge(int* _age)
{
printf("What is your age?\n");
scanf("%d", _age);
}
and in your main()
function you need to call int welcomeMessage(int _age)
as the following:
int main()
{
int _age; // declare variable
getAge(&_age); // calls function
welcomeMessage(_age); // calls function
return 0;
}
And actually, a more correct version of your code should be like the following:
#include <stdio.h>
#include <stdlib.h>
void getAge(int*);
void welcomeMessage(int);
int main()
{
int _age;
getAge(&_age);
welcomeMessage(_age);
return 0;
}
void getAge(int* _age)
{
printf("What is your age?\n");
scanf("%d", _age);
}
void welcomeMessage(int _age)
{
printf("Welcome, you are %d years old.\n", _age)
}
Upvotes: 2
Reputation: 154087
Consider re-writing getAge()
. Be sure to check the result of scanf()
.
int getAge(void) {
int age;
printf("What is your age?\n");
if (1 == scanf("%d", &age)) {
return age;
}
printf("Trouble with input\n");
return 0;
}
Upvotes: 0