很多知識,靠記憶很難掌握;只有實操過後,纔會瞭然於胸。
char c1,c2; cin>>c1; cin>>c2; cout<<c1<<" "<<c2; //輸入a[Enter]b[Enter] //輸出a b
②一參數,get(char ch)
char c1, c2; cin.get(c1); cin.get(c2); cout<<c1<<" "<<c2; //輸入:a[space]b //輸出:a[space][space]
//下面聊聊get(array_name, array_size, endchar)
char c1[10], c2[10];
cin.get(c1, 5, 'a');
cin.get(c2, 5, 'a');
cout<<c1<<endl;
cout<<c2;
//輸入:12a12a
//輸出:12[Enter]
//cin首先從緩衝區中讀取12,遇到結束符'a'停止讀取,'a'留在緩衝區中,c1是12;接下來,cin繼續從緩衝區中讀取數據,讀到的第一個數據是結束符'a',停止讀取,'a'繼續留在緩衝區中,c2是空字符。
//如果要在c1獲得字符後,使c2也能獲得字符,則需要使用cin.ignore()丟掉'a'或者cin.get(char)讀掉'a'。
3.cin.getline(array_name, array_size, endchar);char c, a[10];
cin.getline(a, 5, 'a');
cin.get(c);
cout<<a<<endl;
cout<<c<<endl;
//輸入:11a11
//輸出:11[Enter]1[enter]
//cin.getline將結束符a丟棄
關於第二個不同點的例子:
char c, a[10];
cin.getline(a, 5, 'a');
cin.get(c);
cout<<a<<endl;
cout<<c<<endl;
cout<<(cin.rdstate() & ios::badbit) <<endl;
cout<<(cin.rdstate() & ios::failbit) <<endl;
cout<<(cin.rdstate() & ios::eofbit) <<endl;
//輸入:11111a
//輸出:1111[Enter][Enter]0[Enter]2[Enter]0[Enter]
//解析:cin.getline首先從緩衝區中讀入array_size-1個字符,由於在endchar之前有超過array_size-1個字符,所以cin會報錯,設置fail_bit位,因此,cin.get(char)不會讀入字符。也因此,根據cout的輸出情況,輸出a數組中的字符後,會出現兩個[Enter]。
//輸入:1111a
//輸出:1111[Enter][Enter][Enter]0[Enter]0[Enter]0[Enter]
//解析:a正常讀入array_size-1個字符後,遇到結束符,不會報錯,然後丟棄結束符‘a’,此時緩衝區中還有一個[Enter],這個[Enter]通過cin.get(char)會被c讀取,也因此,在cout時,會出現3個[Enter]。
<--------------------------------------------------------------分割線-------------------------------------------------------------->
4. istream& getline (istream& is, string& str, char delim='\n');
和cin.getline()類似,getline會讀取數據一直到遇到delim(即結束字符endchar)或者文檔結尾或者遇到錯誤。和cin.getline一致,getline也會讀取delim,並丟棄掉。
string str1, str2;
getline(cin, str1, 'a');
getline(cin, str2, 'a');
cout<<str1<<endl;
cout<<str2<<endl;
//輸入:11a[Enter]11a[Enter]
//輸出:11[Enter]11
5. char* gets(char * str) 需要包含<cstdio>
向str所指向的字符數組(C風格)中讀入字符。遇到換行符[Enter]停止或文件結尾,停止;但不會將換行符讀入字符串,空字符null('\0')將會被自動加入到str的結尾。
函數成功後,返回值是str;如果讀取失敗,則返回空指針。
char ch1[20], ch2[20];
gets(ch1);
gets(ch2);
cout<<ch1<<endl;
cout<<ch2<<endl;
//輸入:11a[Enter]11a[Enter]
//輸出:11a[Enter]11a[Enter]
使用gets要注意字符越界的風險。gets和fgets還是有顯著不同的。
6.int getchar(void) 需要包含<cstdio>
從標準輸入中返回字符,返回的字符會被提升爲int。如果達到文件末尾或者錯誤發生,則返回EOF,並且設置相關標誌位。