C++中的getline函數有兩個:ios
1 是iostream類對象的成員函數數組
2 是一個全局函數函數
在C++中爲了使用的方便,C++在標準庫中添加了getline函數。
其實在C++中對不一樣的輸入流對象都定義了一個getline函數,即:
spa
std::fstream::getline
std::istream::getline
std::ifstream::getline
std::iostream::getline
std::wfstream::getline
std::wistream::getline
std::wifstream::getline
std::wiostream::getline
std::stringstream::getline
std::basic_fstream::getline
std::basic_istream::getline
std::istringstream::getline
std::wstringstream::getline
std::basic_ifstream::getline
std::basic_iostream::getline
std::wistringstream::getline
std::basic_stringstream::getline
std::basic_istringstream::getline
這兒咱們討論標準輸入對象的getline函數,其餘的對象的情都是相似的。
在頭文件<iostream>中聲明瞭getline函數:
對象
istream::getline
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
函數是C類型的數組。由於C++中容許對函數進行重載,因此能夠有多個同名函數。delim參數是指定分隔符。若是不指定的話,默認使用'\n'
下面是一個例子:
ci
void test1(){
char line[100];
while(cin.getline(line,100))
cout<<line<<endl;
}字符串
注意這兒的getline是要讀入空白符。可是不包括最後的換行符。
C++中還定義了一個在std名字空間的全局函數,由於這個getline函數的參數使用了string字符串,因此聲明在了<string>頭文件中了。
聲明以下:
get
istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );
簡單的示例以下:
string
void test2(){
string line;
while(getline(cin,line))
cout<<line<<endl;
}io
注意此處也是不讀入換行符的。因此在C++中讀取一行的函數是不讀入換行符的,而GCC中getline函數是讀入換行符的。能夠理解爲,通常狀況下不讀入,特別的是GCC的讀入。