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

-0 -1 +1 12345
2147483647 -2147483648
2147483648 -2147483649
9223372036854775807 -9223372036854775808
stdout
0
-1
1
12345
2147483647
-2147483648
2147483647
-2147483648
2147483647
-2147483648
0
-1
1
12345
2147483647
-2147483648
2147483648
-2147483649
9223372036854775807
-9223372036854775808