0

I'm pretty new to programming so answer to this one might be simple but i can't find it. When checking wether the variable is over 1000 or under 1 the program works but whenever i input a letter the program just loops infinitely. Anyways here's the code and thanks for your help:

printf("Player 1 enter A number between 1 and 1000: ");
scanf("%d", &num);

while(num<1 || num>1000 || !isdigit(num)){
    printf("please enter  different number: ");
    scanf("%d", &num);
}
  • 6
    And what is the return value from `scanf()`? There are reasons such functions have return values, and you just learned one. – Andrew Henle May 08 '18 at 12:14
  • 4
    [`isdigit`](http://www.cplusplus.com/reference/cctype/isdigit/) doesn't do what you think. Read the documentation. What do you think `isdigit(3)` returns? – Jabberwocky May 08 '18 at 12:14

1 Answers1

1

scanf is a poor choice for reading input from the user.

You probably want this:

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

// Get a number from the user
//    number:        pointer to the number
//    return value:  1 if the user has typed a number
//                   0 if the user ha not typed a number

int GetNumber(int *number)
{
  char inputbuffer[20];

  fgets(inputbuffer, sizeof inputbuffer, stdin);  // read raw line from user
  if (!isdigit(inputbuffer[0]))                   // if first char isn't a digit
    return 0;                                     // it's not a number, return 0

  *number = strtol(inputbuffer, NULL, 10);        // convert to number
  return 1;
}


int main()
{
  int num;

  printf("Player 1 enter A number between 1 and 1000: ");

  while (!GetNumber(&num) || num < 1 || num > 1000) {
    printf("please enter different number: ");
  }

  printf("number = %d\n", num);

  return 0;
}

Alternative version of GetNumber:

int GetNumber(int *number)
{
  char inputbuffer[20];

  fgets(inputbuffer, sizeof inputbuffer, stdin);

  char *endptr;
  *number = strtol(inputbuffer, &endptr, 10);
  if (*endptr != '\n')  // if user input ends with somethign else than
    return 0;           // \n it's not a number (e.g: "123a")

  return 1;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • ok this looks a bit more complex than mine xD but thanks for the help, i'll try to understand what is going on in this it'll be a learning experience lol – N. Du Toit May 08 '18 at 13:02
  • @N.DuToit this is a good example of function usage, your main program is much simpler as `GetNumber` handles all the checking if user has entered a number or letters. – Jabberwocky May 08 '18 at 13:04
  • 1
    An input such as `124Hello` will also be accepted and the number `124` extracted while the rest discarded. Could be perfected with a bit more fiddling with `strtol`. +1 – DeiDei May 08 '18 at 13:06
  • @DeiDei yes, that's why I wrote _"There is still room for improvement though"_ – Jabberwocky May 08 '18 at 13:07