I'm making a simple program that asks the user for minimum and maximum values (between 32 and 127, inclusive), but for some reason every time I try to store the minimum value it gets replaced by another value.
Here is the code:
#include <stdlib.h>
#include <stdio.h>
#define lenLimit 256
char text[lenLimit];
int enterNumber(int loLimit, int hiLimit) {
printf("Please enter an integer between 32 and 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) {
for (int i = loLimit; i <= hiLimit; i++) {
printf("ASCII character%3d is %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 is the result:
Please enter an integer between 32 and 127: 31
Min 31 OUT OF range
Please enter an integer between 32 and 127: 33
Min 33 IN range
num returned: 33
num returned: 1600375832
Min: 1600375832
Please enter an integer between 32 and 127: 45
Min 45 IN range
num returned: 45
Max: 45
You are not initialising 'enter' to anything and it is only assigned in 2 out of 3 of your if conditions.
In addition you are calling this function recursively (calling itself), but you are not returning when doing so. Maybe this is intentional, but your comment after the printf makes me think not. This recursion is why you are seeing 2 prints.
Try this...