Ahnaf.Shahriar.Asif's blog

By Ahnaf.Shahriar.Asif, history, 4 years ago, In English

I saw someone to use a function instead of cin/scanf to input a number;

like that :

int n;
n = in();

where in() function is given bellow :

template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch =getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')break;}return (ng?-n:n);}  ?

i don't know what is faster , i also don't know , how scanf or cin works , can anyone please tell me ????

 
 
 
 
  • Vote: I like it
  • -19
  • Vote: I do not like it

»
4 years ago, # |
  Vote: I like it +19 Vote: I do not like it

I wont help you :D :P

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Almost no one knows. Use cin with ios_base::sync_with_stdio(0) and don't think about that

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

The weird looking in function should be faster otherwise what's the point of inventing it?

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

This function should be faster than scanf/cin because it is using getchar() to read data. getchar() is a function in stdio.h that reads and returns a single character from the input, including whitespaces.So what the function in() here is doing is it reads numbers digit by digit and uses them to generate the input number as an int. There also exists a faster version of getchar(), getchar_unlocked() but it does not work in some systems (like Windows). Generally, in terms of speed: getchar_unlocked > getchar > scanf > cin.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    okh , it was fine , but why people downvote me ?? was the question wired ??

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +3 Vote: I do not like it

      Yes :D

    • »
      »
      »
      4 years ago, # ^ |
      Rev. 2   Vote: I like it +3 Vote: I do not like it

      No one wants to waste their time to understand unstructured questions as yours. What even means this title "Help me please :D", and code is not formated as well. But yet I used my time to point out your mistakes.

      How do you expect someone else to spend more time answering you, when you did not invest any.