cin.get();cin.clear();cin.sync()
先看代碼:
#include<iostream> using namespace std; int main(){ int c,x; cout<<"輸入大小"<<endl; cin>>c; x=c+1; cin.sync();//神器;用來清空輸入緩沖區剩余的值的 char a[x]; cout<<"輸入內容"<<endl;//因為輸入大小后直接輸入了回車,回車在緩沖區,沒有被丟棄,所以a[]直接取的緩沖區的值;直接結束; cin.get(a,x);//cin.get的參數應該大1;多出一個填充回車; for(int i=0;i<c;i++){ cout<<a[i]<<endl; } cout<<sizeof(a)<<endl; return 0; }
當不用cin.sync()時,cin一個字符,用“回車”結束,但是cin不讀入“回車”這個字符,所以回車會留在緩沖區,當cin.get()時,它首先讀取緩沖區的內容;然后發現沒有才會讓你在屏幕輸入,但是有內容它就會先讀取,所以馬上就結束了。
cin.get() this function can read "space" to the char array; Like this:cin.get(char*a,int b),"a" is the name of array,"b"is the number of read characters;
tips: because cin.get() also can accept "Enter" ,so we must made the "b" to be "+1" then the number you want.
cin.clear();的作用是清空錯誤的標志;并不是清空緩沖區的;詳情請見:http://www.rzrgm.cn/tonglingliangyong/p/3908463.html
浙公網安備 33010602011771號