Hey every1,

i see every1 uses getchar_unlocked()for accepting 2 space separated integers.

Can any1 please tell me how this function works and how to use it(detailed) because i dont know anything bout this funtion

Thanks in advance

Daksh

Hey every1,

i see every1 uses getchar_unlocked()for accepting 2 space separated integers.

Can any1 please tell me how this function works and how to use it(detailed) because i dont know anything bout this funtion

Thanks in advance

Daksh

1 Like

long long int read_int(){

char r;

bool start=false,neg=false;

long long int ret=0;

while(true){

r=getchar();

if((r-‘0’<0 || r-‘0’>9) && r!=’-’ && !start){

continue;

}

if((r-‘0’<0 || r-‘0’>9) && r!=’-’ && start){

break;

}

if(start)ret*=10;

start=true;

if(r==’-’)neg=true;

else ret+=r-‘0’;

}

if(!neg)

return ret;

else

return -ret;

}

Well , first of all you shouldn’t be using getchar_unlocked() as it is a thread unsafe version of getchar(). People using them are just trying to get a little more faster execution of the program . Rather than that , focus more on the algorithms you need to implement to solve the particular problem , and according the problem specifications , try to get a faster algorithm .

A simple implementation of getchar_unlocked() to take an int as an input will be as follows:-

```
#define getcx getchar_unlocked
inline void inp( int &n )
{
n=0;
int ch=getcx();int sign=1;
while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getcx();}
while( ch >= '0' && ch <= '9' )
n = (n<<3)+(n<<1) + ch-'0', ch=getcx();
n=n*sign;
}
```

So if you know how getchar(); works that is taking the character from the input and putting it into the respective variable , it’s the same for getchar_unlocked().

As speed goes

getchar_unlocked() > getchar() > scanf() > cin .

More could be learnt from here.

Amazing.

Thank for sharing the great help that is valuable.

@admin and others-

I am afraid that this jonclark007 guy seems to be spamming. (the website he shared is related to some research paper writing for students)

Please look into it @admin

Why have you tagged this question as both easy and hard simultaneously?

2 Likes