您的位置:首页 > 其它

<string>函数库中的getline函数

2014-05-14 11:25 507 查看

原型

1、istream& getline ( istream &is , string &str , char delim );
2、istream& getline ( istream& , string& );

参数

is 进行读入操作的输入流
str 存储读入的内容
delim 终结符(其中第二个版本默认为'\n')

返回值

与参数is一样的输入流

简单的例子:

#include <string>
#include <iostream>

using namespace std;

int main(int argc, char** argv) {
string temp;
getline(cin, temp, ';');
cout << temp << endl;
getline(cin, temp, ';');
cout << temp << endl;

return 0;
}


输入样例一:

the first input

the second input; (第一个 ‘ ; ’)

the third input; (第二个 ' ; ')

输出:

the first input

the second input (遇到第一个‘ ; ’后输出)

the third input

可见getline()会从cin流对象的缓存中不断读取字符到temp中直至遇到' ; ',这样我们可以将一些cin原本会忽视的字符如tab,空格,换行符等读进目标字符串;

输入样例二:

the first input;the second input

the third input;

输出:

the first input (遇到第一个' ; '后输出)

the second input

the third input (遇到第二个‘ ; ’后输出)

这个例子也许能更好的说明getline()的实现原理。首先,当我们在键盘中输入the first input;the second input时,cin对象会将其存放进缓冲区,然后由getline按照要求来逐个扫描缓冲区中的字符,当其扫描到the first input后面的‘ ; ’时便停止扫描,并将the first input写进temp中。当第二次调用getline函数时,由于cin的缓冲区中仍然遗留之前输入的the second input,因此getline会继续从这里开始扫描缓冲区直到再次遇到‘
; ’,所以第二次输出的temp会是 the second input (\n) the third input

要说明的一点是,这里的getline与cin.getline没有关系,它是<string>库提供的成员函数,可以理解为string类的友元函数。

PS:cin流输入对象和cout流输出对象其实并不像我们想象中的那么简单,其内部实现我至今仍没有搞懂。希望有大神不吝赐教!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: