原理(大概是)
getchar()比scanf()和cin都要快
利用非常快的讀入函數getchar(),一位一位將數字以字符形式讀入,若讀入的字符不為數字則結束,首先判斷要讀入的數字的正負,之后每讀入一個字符就將字符轉化為數字並*10然后加上它
代碼
這里提供兩種書寫函數的方式
(注意:以下為整型變量的快速讀入函數,讀入其他形式變量請自行修改變量類型)
1 #include<cstdio> 2 using namespace std; 3 4 inline int read1(){
5 int f=1,x=0; 6 char s=getchar(); 7 while(s<'0' || s>'9'){ 8 if(s=='-') 9 f=-1; 10 s=getchar(); 11 } 12 while(s>='0' && s<='9'){ 13 x=x*10+s-'0'; 14 s=getchar(); 15 } 16 return x*f; 17 } 18 19 void read2(int &x){ 20 int f=1; 21 x=0; 22 char s=getchar(); 23 while(s<'0' || s>'9'){ 24 if(s=='-') 25 f=-1; 26 s=getchar(); 27 } 28 while(s>='0' && s<='9'){ 29 x=x*10+s-'0'; 30 s=getchar(); 31 } 32 x*=f; 33 } 34 35 int main(){ 36 int t1,t2; 37 t1=read1(); 38 read2(t2); 39 return 0; 40 }
我感覺還不錯
友情鏈接:安利一只小姐姐的博客