Reputation: 11
I have been working on this program in C, and I don't understand why it is printing beyond the range that parameters state. here is the program, can anyone help me? Also, how do i get the input to reject numbers that arent in specified range? Thanks in advance!
#include <stdlib.h>
#include <stdio.h>
#define LEN 64
int main(){
char line[LEN];
printf("Enter a #, 32-127: ");
fgets(line,LEN,stdin);
int i = atoi(line);
printf("Enter a #, %d-127: ",i);
fgets(line,LEN,stdin);
int j = atoi(line);
for(i;j;i++)
printf("ASCII value of character %d: %c\n",i,i);
return(EXIT_SUCCESS);
}
Upvotes: 1
Views: 96
Reputation: 6914
You need to understand clearly what is this line doing:
for(i;j;i++)
Read more about the for-statement here
for (initialization; condition; increment){
body
}
In your code, j
is your condition
. In C, zero == false
and different from zero is true
. Consequently, j
never becomes zero, so the loop becomes an infinite loop.
Try to explain a little more what are you trying to achieve with the for-statement so we can help you better.
Upvotes: 1
Reputation: 12169
Your "for" loop is incorrect. Instead, try something like:
while ( i <= j ) {
printf("ASCII value of character %d: %c\n",i,i);
i++;
}
or
for ( int idx = i; idx <=j; idx++) {
printf("ASCII value of character %d: %c\n",idx,idx);
}
For validation, just do an "if" statement, and compare the input values to whatever your validation range would be. Leave that to you.
Upvotes: 1