char - Why is my C function returning the incorrect int? -
i'm making simple program asks user minimum , maximum values (between 32 , 127, inclusive), reason every time try store minimum value gets replaced value.
here code:
#include <stdlib.h> #include <stdio.h> #define lenlimit 256 char text[lenlimit]; int enternumber(int lolimit, int hilimit) { printf("please enter integer between 32 , 127: "); fgets(text, lenlimit, stdin); int enter = atoi(text); int exit; if (enter < 32 || enter > 127) { printf("min %i out of range\n", enter); enternumber(enter, hilimit); } if (enter >= 32 && enter <= 127 && hilimit > 127) { exit = atoi(text); printf("min %i in range\n", exit); } if (lolimit >= 32 && lolimit <= 127 && hilimit <= 127 && enter >= lolimit) { exit = hilimit; printf("max %i in range\n", exit); } printf("num returned: %i\n", exit); //prints twice, why? return exit; } void printtable(int lolimit, int hilimit) { (int = lolimit; <= hilimit; i++) { printf("ascii character%3d %c.\n", i, i); } } int main(int argc, char* argv[]) { int min = enternumber(31,128); printf("min: %i\n", min); int max = enternumber(min, 128); printf("max: %i\n", max); printtable(min, max); return(exit_success); }
and here result:
please enter integer between 32 , 127: 31 min 31 out of range please enter integer between 32 , 127: 33 min 33 in range num returned: 33 num returned: 1600375832 min: 1600375832 please enter integer between 32 , 127: 45 min 45 in range num returned: 45 max: 45
you not initialising 'enter' , assigned in 2 out of 3 of if conditions.
in addition calling function recursively (calling itself), not returning when doing so. maybe intentional, comment after printf makes me think not. recursion why seeing 2 prints.
try this...
int enternumber(int lolimit, int hilimit) { printf("please enter integer between 32 , 127: "); fgets(text, lenlimit, stdin); int enter = atoi(text); int exit = enter; if (enter < 32 || enter > 127) { printf("min %i out of range\n", enter); return enternumber(enter, hilimit); } if (enter >= 32 && enter <= 127 && hilimit > 127) { printf("min %i in range\n", exit); } if (lolimit >= 32 && lolimit <= 127 && hilimit <= 127 && enter >= lolimit) { exit = hilimit; printf("max %i in range\n", exit); } printf("num returned: %i\n", exit); //prints twice, why? return exit; }
Comments
Post a Comment