getchar_unlocked()

how to convert input taken by getchar_unlocked() to signed integers…

#define gc getchar_unlocked
void scan(int &x)
{
    register int c = gc();
    x = 0;
    int neg = 0;
    for(;((c<48 || c>57) && c != '-');c = gc());
    if(c=='-') {neg=1;c=gc();}
    for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}
    if(neg) x=-x;
}
1 Like

This function can be used to read both +ve and -ve integers using getchar_unlocked()

int get_num()
{
	int num = 0;
	char c = getchar_unlocked();
	int flag = 0;
	while(!((c>='0' & c<='9') || c == '-'))
		c=getchar_unlocked();
	if(c == '-')
	{
		flag = 1;
		c=getchar_unlocked();
	}
	while(c>='0' && c<='9')
	{
		num = (num<<1)+(num<<3)+c-'0';
		c=getchar_unlocked();
	}
	if(flag==0)
		return num;
	else
		return -1*num;
}

Explanation : getchar_unlocked() is used to read character input. It is very fast compared to printf().

The working of function goes like this…
The first while loop keeps repeating until ‘c’ is given a value of a digit between 0-9 or ‘-’(in case of negative numbers).
If we encounter ‘-’ we initialise flag = 1 to make a note that its negative number later while the function returns the number.
The second while loop keeps repeating until c gets a value of 0-9 and stops when any other character is read(Usually it would be a ’ '(space) or ‘\n’).
The statement num = (num<<3)+(num<<1)+c-'0'; turns character digit in c to integer digit and is added to num*10(Left shift operators. num << a => num * (2^a) ). It can also be written as

num = num*10 + c-'0';  

Finally, we return the value of num depending on value of flag(whether the number is -ve or +ve).

3 Likes

can somebody please explain the working…
thankyou

can I apply this method for scanning long long ???or long long int???

Edited with explanation…

Just replace int with long long int.