getline函数从输入流的下一行读取,并保存读取的内容到str中,包括空格符,但不包括换行符。getline 函数将istream 参数作为返回值,和输入操作符一样也把它用作判断条件。
范例:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string line;
while(<span style="color:#ff0000;">getline(cin,line)</span>)
cout<<line<<endl;
return 0;
}
getline()函数的语法:
istream &getline( char *buffer, streamsize num );
istream &getline( char *buffer, streamsize num, char delim );
getline()函数用于输入流,读取字符到buffer中,直到下列情况发生:
num - 1个字符已经读入,碰到一个换行标志,
碰到一个EOF,
或者,任意地读入,直到读到字符delim。delim字符不会被放入buffer中。
getline原型如下:
getline(char* c,int i,char c); 表示读入i个字符,或者遇到结束符c为止的字符数,保存到c中。
getline(char*,int); 表示读入i个字符到c中。注意读入的字符数应比实际的大1,因为读入的是字符串,字符串将会以\0'作为结束,如果你要读入3个字符,那么i的值应该为4。
注意getline会读取并丢弃分界符。
例如:
#include<iostream>
#include<string>
using namespace std;
int const MAX=1048577;
char txt[MAX];
int main()
{
<span style="color:#ff0000;">cin.getline(txt,MAX,'\n');</span>
return 0;
}