代碼:
1 #include <iostream> 2 #include <cstdio> 3 4 using namespace std; 5 6 int main(){ 7 8 char* s; 9 s = new char[50]; //必須要分配空間 10 cin.getline(s,5); 11 int i = 0; 12 while(s[i] != '\0'){ 13 cout<<s[i]; 14 i++; 15 } 16 cout<<endl<<i<<endl; 17 cin.clear(); //當failbit位為1時需要clear,否則后面的getline讀取為空字符串 18 19 string str; 20 getline(cin,str); 21 cout<<str<<endl; 22 getline(cin,str,'#'); 23 cout<<str<<endl; 24 getline(cin,str); 25 cout<<str<<endl; 26 27 return 0; 28 }
輸入輸出:
(input)slkdsa;34 slkd 4 sa;34 (input)hel#id hel id
分析:
C++中有兩個getline函數,一個是在string頭文件中,定義的是一個全局的函數,函數聲明是istream& getline ( istream& is, string& str, char delim )與istream& getline ( istream& is, string& str );
另一個則是istream的成員函數,函數聲明是istream& getline (char* s, streamsize n )與istream& getline (char* s, streamsize n, char delim );注意第二個getline是將讀取的字符串存儲在char數組中而不可以將該參數聲明為string類型,因為C++編譯器無法執行此默認轉換。
getline函數大致流程:
1、首先判斷istream的failbit位是否為1,為1的話意味着輸入流的狀態有錯誤,則不進行讀操作,getline函數結束執行
2、從當前位置開始從輸入流中依次讀取單個字符並拷貝到緩沖區,直到遇到下列條件滿足時,循環結束。
(1)遇到文件尾時停止讀操作,並設置流對象的結束標記為1
(2)讀到調用者指定的分隔符時,此時將分隔符之前的字符拷貝到緩沖區中,但分隔符本身不拷貝進去,並且下次讀操作將從分隔符后的下一個字符開始。
(3)已經讀了n-1個字符(n是調用者傳入的第二個實參_Count的初值),此時要把流對象的錯誤標志位置1
利用getline連續讀取直至文末
1 #include <iostream> 2 #include <cstdio> 3 4 using namespace std; 5 6 int main(){ 7 8 string s; 9 while(getline(cin,s)){ 10 cout<<s<<endl;; 11 } 12 13 return 0; 14 }