fork(1) download
  1. // Read an integer from standard input.
  2. // @note Consume all decimal digits; saturate on overflow.
  3.  
  4. int readInt() @nogc
  5. {
  6. import core.stdc.ctype : isspace;
  7. import core.stdc.stdio : getchar, ungetc, stdin;
  8. import std.experimental.checkedint : checked, Saturate;
  9.  
  10. int c;
  11. do
  12. {
  13. c = getchar();
  14. }
  15. while (isspace(c));
  16.  
  17. bool negative = false;
  18.  
  19. switch (c)
  20. {
  21. default : break;
  22. case '-': negative = true;
  23. goto case '+';
  24. case '+': c = getchar();
  25. }
  26.  
  27. int result = 0;
  28.  
  29. for (int digit; uint(digit = c - '0') < 10; c = getchar())
  30. {
  31. // Subtract to utilize larger magnitude of negative.
  32. result = (result.checked!Saturate * 10 - digit).get;
  33. }
  34.  
  35. ungetc(c, stdin);
  36. return negative ? result : (-result.checked!Saturate).get;
  37. }
  38.  
  39. void main()
  40. {
  41. import std.stdio;
  42.  
  43. int n = 10;
  44.  
  45. for (int i = 0; i < n; i++)
  46. {
  47. writeln(readInt());
  48. }
  49. }
Success #stdin #stdout 0s 5328KB
stdin
-0
-1
+1
12345
2147483647
-2147483648
2147483648
-2147483649
9223372036854775807
-9223372036854775808
stdout
0
-1
1
12345
2147483647
-2147483648
2147483647
-2147483648
2147483647
-2147483648