一: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/