0
#include <stdio.h>
#include <string.h>
#include <ctype.h>


int main(void){
    int corX = 0;

    do{
        printf("Please enter number X:\n");
        scanf("%d",&corX);
    } while(!(isdigit(corX) && corX>1 && corX<80));

    printf("You entered X as: %d\n",corX);
    return 0;
}

Hi! The code above should check if the entered value is an integer and fit to the range. If not, program should ask again. Unfortunately, it does not work in this way. Whatever I write, loop always go through and in a result I receive entered number for numbers and 0 for other signs. Could somebody explain, what I am doing wrong?

pklimczu
  • 626
  • 1
  • 6
  • 15

1 Answers1

1

there seems to be a problem in your while condition. I rewrote it and I get what I think is the behavior you wanted (ask for input when input smaller 1 or greater 80)

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int clean_stdin()
{
  while (getchar()!='\n');
  return 1;
}


int main(void){
    int corX = 0;

    do{
        printf("Please enter number X:\n");
        scanf("%d",&corX);
    } while( ( corX<1 || corX>80 ) && clean_stdin() );

    printf("You entered X as: %d\n",corX);
    return 0;
}

edit: I did not check my initial post careful enough. The checking for isdigit is not needed at all as you already are using %d in scanf, I removed it completely from the while condition. As quick fix for the infinite loop problem I added the clean_stdin() function that is mentioned in the accepted answer of this post How to scanf only integer and repeat reading if the user enter non numeric characters? that @Gangadhar mentioned in his comment and which I recommend for reading (which also I should have done before posting)

Community
  • 1
  • 1
Erik
  • 2,137
  • 3
  • 25
  • 42
  • Thank you very much, it almost works - but why in case of writing sign which is not a number, program falls into an infinity loop asking again and again "Please enter number X:"? – pklimczu Nov 10 '13 at 14:54
  • This solution is not valid. `isdigit(corX)` checks if corX is in ASCII range '0'-'9' which differs from the values of corX (0-9 integers) which `corX` obtains when a digit is inputed with `%d` formatting. This means that `isdigit(corX)` **always** returns 0, i.e. `!isdigit(corX)` **always** returns a non-zero when any digit is typed in. `scanf` should read like `scanf("%c",&corX)`. – Igor Popov Nov 10 '13 at 16:38
  • @IgorPopov I tried to amend my answer to hopefully improve it. I take your point that my answer did not cover everything (and probably still doesn't) – Erik Nov 10 '13 at 17:20