<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流输出对象其实并不像我们想象中的那么简单,其内部实现我至今仍没有搞懂。希望有大神不吝赐教!
相关文章推荐
- <string.h>函数集合
- 整理:CString类的完美总结&&CString 成员函数用法大全&&string 与 CString 转化&&<string><string.h> 和<cstring>的区别
- <转>C语言中的文件输入输出函数
- <string.h> <string> 和<CString>
- < Unity 3D专栏 >添加控件检测事件,函数处理
- <string>和<string.h>两头文件区别
- <string> 与<string.h>、<cstring>的区别
- <math.h>中的数学函数汇总
- <MFC>CString和<C++>标准库string的区别,及判断字符串是否为空
- <<C语言深度剖析>>学习之七之函数
- <Linux+Qt>char*,QString,String类型的相互转换
- <Linux+Qt>计时函数
- <python>Python的函数参数传递:传值?引用?
- c<string.h>函数
- <string>头文件
- StrCat <shlwapi.h> strcat <string.h> wcscat <string.h>
- <<c++ primer>> 函数指针的笔记
- <string> 与 <string.h> 的区别
- <c:if test="${fn:contains(name, searchString)}">
- <类模板 的 成员函数的特化>及<类 的 成员模板函数的特化>