標籤:
主要的輸入輸出函數有6種:cin, cin.get() , cin.getline() ,getline() , gets() ,getchar()
cin
(1)根據變數的類型讀取資料
結束條件:斷行符號鍵、空格鍵、TAB
結束符的處理:緩衝區中丟棄使輸入結束的結束符(斷行符號鍵、空格鍵、TAB)
#include <iostream>using namespace std;void main(){ int a,b; cin>>a>>b; cout<<a+b<<endl;}
(2)接收字串
#include <iostream>using namespace std;void main(){ char ch[20]; cin>>ch; cout<<ch<<endl;}
輸入:helloworld
輸出:helloworld
輸入:hello world(此時是空格鍵,表示輸入結束)
輸出:hello
cin.get()
(1)接收一個字元
結束條件:斷行符號鍵
結束符處理:緩衝區的Enter不丟棄
#include <iostream>using namespace std;void main(){ char ch; //ch = cin.get(); cin.get(ch); cout<<ch<<endl;}
輸入:he llo
輸出:h
(2)接收一行字串,cin.get(數組名,接收字元的數目),
結束條件:Enter
結束符處理:緩衝區的Enter丟棄
#include <iostream>using namespace std;void main(){ char ch[20]; cin.get(ch,10); cout<<ch<<endl;}
輸入:hello world
輸出:hello wor(9個字元加上‘/0‘)
cin.getline()
接收一個字串可以接受空格,
cin.getline(數組名,長度,結束符) 與 cin.get(數組名,長度,結束符)用法是一樣的
區別:當輸入的字串的長度超過指定的長度時,cin.getline()會出錯,cin不會執行。
而cin.get()繼續執行下次是從緩衝區內去字元
結束條件:Enter
結束符處理:丟棄Enter
#include <iostream>using namespace std;void main(){ char name[20]; char shcool[30]; cin.getline(name,10); cin.getline(shcool,20); cout<<"name:"<<name<<endl; cout<<"shcool:"<<shcool<<endl;}
可以看到是上面的輸出的區別。
getLine()
接收字串,可以接受空格,是String流,注意標頭檔
#include <iostream>#include <string>using namespace std;int main (){ string str; getline(cin,str); cout<<str<<endl;}
gets()
#include <iostream>#include <string>using namespace std;int main (){ char ch[20]; gets(ch); cout<<ch<<endl;}
getchar()
接收一個字元,是C語言的函數,
#include <iostream>#include <string>using namespace std;int main (){ char ch; ch = getchar(); cout<<ch<<endl;}
C++常用的輸入函數總結