C++中有两个getline函数, cin.getline()与getline() 
这两个函数相似,但是 这两个函数分别定义在不同的头文件中。
 
cin.getline()属于istream流,而getline()属于string流,是不一样的两个函数

1.getline()是定义在<string>中的一个行数,用于输入一行string,以enter结束。

getline()的原型是istream& getline ( istream &is , string &str , char delim );
其中 istream &is 表示一个输入流,譬如cin;string&str表示把从输入流读入的字符串存放在这个字符串中(可以自己随便命名,str什么的都可以);char delim表示遇到这个字符停止读入,在不设置的情况下系统默认该字符为'\n',也就是回车换行符(遇到回车停止读入)。

函数原型:istream& getline ( istream &is , string &str , char delim );
is:istream类的输入流对象,譬如cin;
str:待输入的string对象,表示把从输入流读入的字符串存放在这个字符串中(可以自己随便命名,str什么的都可以);
delim:表示遇到这个字符停止读入,在不设置的情况下系统默认该字符为'\n',也就是回车换行符(遇到回车停止读入)。

example 1:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
string fstr;
string lstr; int main(int argc, char* argv[])
{
cout<<"first str: \n";
getline(cin,fstr);
cout<<"last str: \n";
getline(cin,lstr); cout<<"first str:"<<fstr<<","<<"last str:"<<lstr<<endl;
system("pause");
return(0);
}

  

example 2:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std; int main(int argc, char* argv[])
{
string line;
cout<<"please cin a line:";
getline(cin,line,'#');
cout<<endl<<"The line you give is:"<<line<<endl;
return(0);
}

  

2.cin.getline(char ch[],size)是cin 的一个成员函数,定义在<iostream>中,用于输入行指定size的字符串,以enter结束。若输入长度超出size,则不再接受后续的输入。

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
char fstr[6] ;
char lstr[7]; int main(int argc, char* argv[])
{
cout<<"first str: \n";
cin.getline(fstr,6); cout<<"last str: \n"; cin.getline(lstr,7); cout<<"first str:"<<fstr<<","<<"last str:"<<lstr<<endl;
system("pause");
return(0); }

  

这里注意,如果在输入”first str“的时候,输入的字符数多余5个的话,会感觉到    cin.getline(lstr,7);  没有执行

如下图:

为什么呢,因为你输入进去的”wertyuioop”过长,cin函数出错了~

cin有一些函数进行错误处理。这里需要在“cin.getline(fstr,6);”后面加以下两行代码:

cin.clear();//清除错误标志
cin.ignore(1024,'\n');//清除缓存区数据

然后运行就会有了

关于cin出错以及解决方法还在整理中~整理好后放一个连接到这里来~

最新文章

  1. 《转载》跟我学SpringMVC
  2. Yii 1开发日记 -- 搜索功能及Checkbox的实现
  3. [问题记录.VisualStudio]VS2013无法新增和打开项目
  4. Windows Azure Virtual Machine (28) 使用Azure实例级别IP,Instance-Level Public IP Address (PIP)
  5. MySQL优化经验和方法汇总
  6. MVC学习中遇到问题
  7. 解决服务器复制中SID冲突问题
  8. ren
  9. Passbook教程中生成pass时遇到的“Couldn&#39;t find a passTypeIdentifier in the pass”
  10. (转)实战p12文件转pem文件
  11. 【转】Windows与Linux(Ubuntu)双系统时间不一致的解决方法
  12. Oracle EBS-SQL (MRP-5):重起MRP Manager.sql
  13. DOM操作-克隆元素
  14. 关于cocos2d-x面试的问题
  15. Java贪吃蛇感想
  16. Ex4_21 最短路径算法可以应用于货币交易领域..._第十二次作业
  17. Python中正则表达式的巧妙使用
  18. 刨根究底字符编码之—UTF-16编码方式
  19. python简说(十二)time模块
  20. Java编程的逻辑 (6) - 如何从乱码中恢复 (上)?

热门文章

  1. 记录 C++ STL 中 一些好用的函数--持续更新 (for_each,transform,count_if,find_if)
  2. Java 常用类String类、StringBuffer类
  3. 软工 &#183; 第十一次作业 - Alpha 事后诸葛亮(团队)
  4. mysql---时间类型详解
  5. HDU 5183 Negative and Positive (NP) 前缀和+哈希
  6. Scrum团队成立及《构建之法》第六、七章读后感
  7. (五)Jmeter中的属性和变量
  8. paoding-rose 之 maven配置
  9. 第181天:HTML5——视频、音频
  10. (一)Quartz2.2.1 简单例子