Question but maybe something very simple I overlook here. I am trying to put a scanf function inside a function. Is this possible like in the following example? When I try to do this, Main does not seem to receive the value passed back from makechoice and the final number is always 0.
#include <stdio.h>
#include <stdlib.h>
int makechoice(int choice) {
printf("Make a choice\n");
scanf("%d", &choice);
return choice;
};
int main() {
int choice;
makechoice(choice);
printf("The number that the function makechoice returned is %d", choice);
return 0;
};
CodePudding user response:
It is absolutely possible to call scanf inside a function. However, C function arguments are passed by value. This means that the changes made to choice in makechoice are just to that function argument. They have no bearing on the choice in main.
You have returned that value from makechoice, but never use that returned value in main.
You may be looking for something more like:
#include <stdio.h>
int make_choice() {
int temp;
scanf("%d", &temp);
return temp;
}
int main(void) {
int choice = makechoice();
printf("The number that the function makechoice returned is %d", choice);
return 0;
}
CodePudding user response:
There are 2 major approaches you can take. Rather than a verbose description, I'll just give some sample code:
#include <stdio.h>
#include <stdlib.h>
int
makechoice1(void)
{
int choice;
printf("Make a choice\n");
if( scanf("%d", &choice) != 1 ){
fprintf(stderr, "Invalid input\n");
exit(1);
}
return choice;
}
int
makechoice2(int *choice)
{
printf("Make a choice\n");
if( scanf("%d", choice) != 1 ){
return 1;
}
return 0;
}
int
main(void)
{
int choice
choice = makechoice1();
printf("The number that the function returned is %d\n", choice);
if( makechoice2(&choice) ){
fprintf(stderr, "The function failed\n");
} else {
printf("The number that the function returned is %d\n", choice);
}
return 0;
};
