2

I'm checking my code with different inputs. I have for example the next code:

if((scanf("%d",&n)!=1)) {
  printf("Invalid number\n");
  return 0;
}

if i'll try to scan a higher number of int than allowed (for example: 10000000000), it won't print "Invalid number". I want it to print and end the program. what to do?

kicklog
  • 109
  • 2
  • 8
  • Related: https://stackoverflow.com/questions/28007600/detecting-integral-overflow-with-scanf – myaut Oct 30 '17 at 18:53
  • You could use a long and then check if the long is within the int bounds. Or you could use a string. – MFisherKDX Oct 30 '17 at 18:54
  • @interjay.: I missed the part...it reads the number but as it overflown then the number will be something unexpected – user2736738 Oct 30 '17 at 18:55
  • https://stackoverflow.com/questions/9438954/c-check-that-an-int-read-by-scanf-is-in-the-range-of-the-integers – MFisherKDX Oct 30 '17 at 18:55

1 Answers1

0

Number of read items would be 1 but as int would not be able to hold the value it would hold something other than what is entered. Because 32 bit signed int(most likely the case) won't be able to hold that number. As a result it will contain some garbage value.

user2736738
  • 30,591
  • 5
  • 42
  • 56