Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

c++ - getchar_unlocked( ) VS scanf() VS cin

What is the difference among these three input functions in programming language. Do they input in different ways from each other?

1.getchar_unlocked()

 #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;
  }   

2.scanf("%d",&n)

3.cin>>n

Which one takes least time when input the integers?

I use THese header files in c++ where all 3 cased run in c++;

  #include<iostream>
  #include<vector>
  #include<set>
  #include<map>
  #include<queue>
  #include<stack>
  #include<string>
  #include<algorithm>
  #include<functional>
  #include<iomanip>
  #include<cstdio>
  #include<cmath>
  #include<cstring>
  #include<cstdlib>
  #include<cassert>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Two points to consider.

  1. getchar_unlocked is deprecated in Windows because it is thread unsafe version of getchar().

  2. Unless speed factor is too much necessary, try to avoid getchar_unlocked.

Now, as far as speed is concerned.

    getchar_unlocked > getchar

because there is no input stream lock check in getchar_unlocked which makes it unsafe.

    getchar > scanf

because getchar reads a single character of input which is char type whereas scanf can read most of the primitive types available in c.

    scanf > cin (>> operator)

because check this link

So, finally

getchar_unlocked > getchar > scanf > cin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...