fast reading example

Source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29


inline int (void);
inline int read_unsigned(void);

int main(void) {

int a = read();
int b = read_unsigned();
// DO NOT use something like:
// int a = read(), b = read();
// it will NOT work CORRECTLY
int c = read();
int d = read_unsigned();

printf("a = %2dn"
"b = %2dn"
"c = %2dn"
"d = %2dn",
a, b, c, d
);
/* Output :
a = 2
b = 2
c = -2
d = 2 // the input for c is -2, but read_unsigned() will drop the '-'
*/

return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<cctype>
// provide isdigit(),
// which can judge whether a char
// is a digit -> returns true
// or not -> returns false

/*
* read() & read_unsigned()
* @brief Read a number.
* @return read() returns the next number in the buffer.
* read_unsigned() returns the number with no sign
*
* Read a number digit by digit.
* Much FASTER than scanf() ONLY when you need to read a LARGE NUMBER of numbers.
* read_unsigned() is NOT ABLE to read NEGATIVE number.
*
* Example: 123 => 1 = 1
* 1 * 10 + 2 = 12
* 12 * 10 + 3 = 123
*
* Code Author : Xeon.Stin.
*/


inline int (void) {
char ch;
while (!(isdigit(ch = getchar()) || ch == '-'));
// judge whether the number is negative
int res = 0, flg = 1;
// and get rid of those not-digit chars
if (ch == '-') flg = -1;
// judge whether the number is negative
else res = ch - '0';
// the first digit of number
while (isdigit(ch = getchar()))
// read the other digits of number
(res *= 10) += ch - '0';
// means: res = res * 10 + ch - '0';
return res * flg;
// returns a signed number
}

inline int read_unsigned(void) {
char ch;
while (!isdigit(ch = getchar())); // get rid of those not-digit chars
int res = ch - '0'; // the first digit of number
while (isdigit(ch = getchar())) // read the other digits of number
(res *= 10) += ch - '0'; // means: res = res * 10 + ch - '0';
return res; // returns a unsigned number
}