一、getline函数的用法:
getline只要一遇到换行符就结束读取操作并返回结果,哪怕一开始输入的是换行符也是如此。
C++中有两个getline函数,一个是在string头文件中:定义的是一个全局的函数,
函数声明是:istream& getline ( istream& is, string& str, chardelim );或
istream& getline (istream& is, string& str );
注意:chardelim是截止限定符,默认是回车.
例子:
ifstream infile("a.txt");
while (!infile.eof())
{
string str;
getline(infile,str);
cout<<str<<endl;
}
string str;
while (getline(cin,str))//一行带空格的字符串
{
}
一个是在istream的成员函数:存在char数组中。
函数声明是:istream& getline (char* s, streamsize n );或
istream& getline (char* s, streamsize n, chardelim );
例子:
char c[10];
ifstream infile("a.txt");
while (!infile.eof())
{
infile.getline(c,10);
cout<<c<<endl;
}
注意:
1.char str[20];cout<<str;输出字符串时,cout流中用数组名。
2.若char str[20]; cin>>str;若超出str数组的长度20,则多余的字符顺序存放到str数组的字节中,可能破坏其他的数据。
3.string s;cin>>s;将string对象读入s,遇到空白停止。