0

I want to know how to keep taking inputs from keyboard with this condition: If the given input is a positive number, it keeps going with the code If the given input is a negative number or a letter, it must print "insert a positive number" and then ask again for another input until it has the correct one. About negative and positive inputs the code i wrote works great, but it bugs out when I put a letter. The check I tried is the following

chk=isalpha(n);
while(!chk || n<0)
{
    printf("Inserire un intero positivo \n");
    scanf("%d", &n);
    chk=isalpha(n);
}
printf("%d\n%d\n", t1, t2);

In this case if I put a negative number it works correctly, but if I type a letter the printf loops. I also tried while(isalpha(n) || n<0) And a bunch of other pieces of code I'll skip for you. Please help me figure this out

Dillon Wreek
  • 53
  • 1
  • 9
  • 1
    You should check the return value of `scanf`. Or ditch it altogether in favor of `fgets`. – Eugene Sh. Oct 11 '18 at 19:13
  • 1
    Your question is not really about C. It is about `scanf`. If you want to learn C, the best possible advice is: do *not* use scanf. Ever. – William Pursell Oct 11 '18 at 19:15
  • 1
    You can't use `isalpha` to accomplish this. That will check the value of `n` and return true if it's one of the alphabetic character codes. For example, if the user enters 97 it will return true because 97 is the ASCII representation of the letter 'a'. – Carey Gregory Oct 11 '18 at 19:18

1 Answers1

0

You can check return value of scanf in case of char it returns 0 along with that you need to clear the buffer to stop scanf consuming the same character.

Example:

int ret = 0;
do
{
     char c;
     while ((c = getchar()) != '\n' && c != EOF) { } /* to clear the bad characters*/

     printf("Inserire un intero positivo \n");
     ret = scanf("%d", &n);
}while(!ret || n<0);
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
  • _but if I type a letter the printf loops._ Your code will, too. – 001 Oct 11 '18 at 19:23
  • @JohnnyMopp That is what intended behavior. User is supposed to enter valid number. – kiran Biradar Oct 11 '18 at 19:28
  • `If the given input is a negative number or a letter, it must print "insert a positive number" and then ask again for another input until it has the correct one. ` This is exactly is OP's need. – kiran Biradar Oct 11 '18 at 19:29
  • 1
    I guess Johnny is meaning that the `scanf` won't consume any input, so it will loop over and over on the same faulty part. https://ideone.com/m95PAD You need to clean up the bad characters before retrying. – Eugene Sh. Oct 11 '18 at 19:46
  • @EugeneSh. Exactly it is. Thank you – kiran Biradar Oct 11 '18 at 19:48
  • Professor told me to do this way while(scanf("%d",&n) != 1 || n<0) { printf("Inserire un intero positivo\n"); while(getchar() != '\n'); } – Dillon Wreek Oct 12 '18 at 20:56