cin.getline()与getline()

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表示遇到这个字符停止读入,在不设置的情况下系统默认该字符为' ',也就是回车换行符(遇到回车停止读入)。

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

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: 
";  
    getline(cin,fstr); 
    cout<<"last str: 
";  
    getline(cin,lstr);  
    
    cout<<"first str:"<<fstr<<","<<"last str:"<<lstr<<endl;  
    system("pause");  
    return(0);  
}  
 

  

image

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);  
}  
 

  

image

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: 
";  
        cin.getline(fstr,6); 
    
        cout<<"last str: 
";  
       
        cin.getline(lstr,7);  
        
        cout<<"first str:"<<fstr<<","<<"last str:"<<lstr<<endl;  
        system("pause");  
        return(0);  
  
} 

  

image

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

如下图:

image

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

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

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

image

然后运行就会有了

image

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

原文地址:https://www.cnblogs.com/hhddcpp/p/4308974.html