getline函數是一個比較常見的函數。根據它的名字我們就可以知道這個函數是來完成讀入一行數據的。現在對getline函數進行一個總結。
在標准C語言中,getline函數是不存在的。std::fstream::getline這兒我們討論標准輸入對象的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
istream::getline函數是C類型的數組。因為C++中允許對函數進行重載,所以可以有多個同名函數。delim參數是指定分隔符。如果不指定的話,默認使用'\n'
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
istream& getline ( istream& is, string& str, char delim );簡單的示例如下:
istream& getline ( istream& is, string& str );
#define _GNU_SOURCE #includeC++格式的cin.getline()#include ssize_t getline(char **lineptr, size_t *n, FILE *stream); int main(void) { FILE *fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen("/etc/motd", "r"); if (fp == NULL) exit(EXIT_FAILURE); while ((read = getline(&line, &len, fp)) != -1) { printf("Retrieved line of length %zu :\n", read); printf("%s", line); } if (line) free(line); exit(EXIT_SUCCESS); }
#includeusing namespace std; int main( ) { cout << "Type the letter 'a': "; ws( cin ); char c[10]={'\0'}; cin.getline(c,10,'#');//將getline換成get試試,情況就大不相同了 cout< C++中有兩個getline函數,這兩個函數分別定義在不同的頭文件中。 1.getline()是定義在 中的一個行數,用於輸入一行string,以enter結束。 函數原型:getline(cin,str); cin:istream類的輸入流對象 str:待輸入的string對象 //《C++ primary plus》第四章編程練習題1 #include#include using namespace std; string fname; string lname; char grade; int age; int main() { cout<<"What is your first name?"; getline(cin,fname); cout<<"What is your last name?"; getline(cin,lname); cout<<"What letter grade do you deserve?"; cin>>grade; cout<<"What is your age?"; cin>>age; cout<<"Name:"< 2.cin.getline(char ch[],size)是cin 的一個成員函數,定義在 中,用於輸入行指定size的字符串,以enter結束。若輸入長度超出size,則不再接受後續的輸入。 //《C++ primary plus》第四章編程練習題1 #includeusing namespace std; char fname[5]; char lname[5]; char grade; int age; int main() { cout<<"What is your first name?"; cin.getline(fname,5); cout<<"What is your last name?"; cin.getline(lname,5); cout<<"What letter grade do you deserve?"; cin>>grade; cout<<"What is your age?"; cin>>age; cout<<"Name:"<