C++中有兩個getline函數, cin.getline()與getline()
這兩個函數相似,但是 這兩個函數分別定義在不同的頭文件中。
cin.getline()屬於istream流,而getline()屬於string流,是不一樣的兩個函數
1.getline()是定義在<string>中的一個行數,用於輸入一行string,以enter結束。
getline()的原型是istream& getline ( istream &is , string &str , char delim );
其中 istream &is 表示一個輸入流,譬如cin;string&str表示把從輸入流讀入的字符串存放在這個字符串中(可以自己隨便命名,str什么的都可以);char delim表示遇到這個字符停止讀入,在不設置的情況下系統默認該字符為'\n',也就是回車換行符(遇到回車停止讀入)。
函數原型:istream& getline ( istream &is , string &str , char delim );
is:istream類的輸入流對象,譬如cin;
str:待輸入的string對象,表示把從輸入流讀入的字符串存放在這個字符串中(可以自己隨便命名,str什么的都可以);
delim:表示遇到這個字符停止讀入,在不設置的情況下系統默認該字符為'\n',也就是回車換行符(遇到回車停止讀入)。
example 1:
#include "stdafx.h" #include <iostream> #include <string> using namespace std; string fstr; string lstr; int main(int argc, char* argv[]) { cout<<"first str: \n"; getline(cin,fstr); cout<<"last str: \n"; getline(cin,lstr); cout<<"first str:"<<fstr<<","<<"last str:"<<lstr<<endl; system("pause"); return(0); }
example 2:
#include "stdafx.h" #include <iostream> #include <string> using namespace std; int main(int argc, char* argv[]) { string line; cout<<"please cin a line:"; getline(cin,line,'#'); cout<<endl<<"The line you give is:"<<line<<endl; return(0); }
2.cin.getline(char ch[],size)是cin 的一個成員函數,定義在<iostream>中,用於輸入行指定size的字符串,以enter結束。若輸入長度超出size,則不再接受后續的輸入。
#include "stdafx.h" #include <iostream> #include <string> using namespace std; char fstr[6] ; char lstr[7]; int main(int argc, char* argv[]) { cout<<"first str: \n"; cin.getline(fstr,6); cout<<"last str: \n"; cin.getline(lstr,7); cout<<"first str:"<<fstr<<","<<"last str:"<<lstr<<endl; system("pause"); return(0); }
這里注意,如果在輸入”first str“的時候,輸入的字符數多余5個的話,會感覺到 cin.getline(lstr,7); 沒有執行
如下圖:
為什么呢,因為你輸入進去的”wertyuioop”過長,cin函數出錯了~
cin有一些函數進行錯誤處理。這里需要在“cin.getline(fstr,6);”后面加以下兩行代碼:
cin.clear();//清除錯誤標志
cin.ignore(1024,'\n');//清除緩存區數據
然后運行就會有了
關於cin出錯以及解決方法還在整理中~整理好后放一個連接到這里來~