getline和cin.getline

C++中有两个getline函数,这两个函数分别定义在不同的头文件中。

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

函数原型:getline(cin,str);
cin:istream类的输入流对象
str:待输入的string对象

example 1:

#include <iostream> 
#include <string> 
using namespace std;  
string fname;  
string lname;  
char grade;  
int age;  
int main()  
{  
   cout<<"What is your first name?";  
   getline(cin,fname);  
   cout<<"What is your last name?";  
   getline(cin,lname);  
   cout<<"What letter grade do you deserve?";  
   cin>>grade;  
   cout<<"What is your age?";  
   cin>>age;  
   cout<<"Name:"<<lname<<","<<fname<<endl<<"Grade:"   <<grade<<endl<<"Age:"<<age<<endl;  
   system("pause");  
   return(0);  
}  

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

example 2:


#include <iostream> 
using namespace std;  
char fname[5];  
char lname[5];  
char grade;  
int age;  
int main()  
{  
    cout<<"What is your first name?";  
    cin.getline(fname,5);  
    cout<<"What is your last name?";  
    cin.getline(lname,5);  
    cout<<"What letter grade do you deserve?";  
    cin>>grade;  
    cout<<"What is your age?";  
    cin>>age;  
    cout<<"Name:"<<lname<<","<<fname<<endl<<"Grade:"<<grade<<endl<<"Age:"<<age<<endl;  
    system("pause");  
    return(0);  
}  

你可能感兴趣的:(getline和cin.getline)