一:istream類的公共成員函數getline()
1.函數入口形式為:(1.1)istream& getline(char *s,stream_size n);
(1.2)istream& getline(char*s,streamsize n,char delim);
2.函數功能為:
函數(1.1)功能為取輸入流字符,並以字符串形式存貯於s所指空間,直到讀取了n-1個字符或者讀到‘\n’字符為止
(讀取字符中不包括‘\n’但是,程序會在s空間末尾加上‘\n’,就相當於讀取了‘\n’),函數返回值為輸入流引用類型即,
當前輸入流的引用。
函數(1.2)功能為取輸入流字符,並以字符串形式存貯於s所指空間,直到讀到了,字符delim(單不讀取delim)
或者n-1個字符或者讀到‘\n’字符為止(讀取字符中不包括‘\n’但是,程序會在s空間末尾加上‘\n’,就相當於讀取了‘\n’),
函數返回值為輸入流引用類型即,當前輸入流的引用。
3.舉例:
#include <iostream> // std::cin, std::cout int main () { char name[256], title[256]; std::cout << "Please, enter your name: "; std::cin.getline (name,256); std::cout << "Please, enter your favourite movie: "; std::cin.getline (title,256); std::cout << name << "'s favourite movie is " << title; return 0; }
輸入名字:Jonathan 輸入電影名:《up in the air》
輸出: Jonathan's favourite movie is 《up in the air》
二: 頭文件<string>定義函數getline()
1.函數入口形式為:(2.1)istream& getline(istream& in,string& str,char delim);
(2.2)istream& getline(istream& in,string& str);
2功能描述:Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).
3舉例:
// extract to string #include <iostream> #include <string> int main () { std::string name; std::cout << "Please, enter your full name: "; std::getline (std::cin,name); std::cout << "Hello, " << name << "!\n"; return 0; }
參考:http://www.cplusplus.com/reference/istream/istream/getline/
http://www.cplusplus.com/reference/string/string/getline/