cin.getline()与getline()

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


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

 

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

 

 

example 1:

[cpp]  view plain copy
  1. //《C++ primary plus》第四章编程练习题1  
  2. #include <iostream>  
  3. #include <string>  
  4. using namespace std;  
  5. string fname;  
  6. string lname;  
  7. char grade;  
  8. int age;  
  9. int main()  
  10. {  
  11.    cout<<"What is your first name?";  
  12.    getline(cin,fname);  
  13.    cout<<"What is your last name?";  
  14.    getline(cin,lname);  
  15.    cout<<"What letter grade do you deserve?";  
  16.    cin>>grade;  
  17.    cout<<"What is your age?";  
  18.    cin>>age;  
  19.    cout<<"Name:"<<lname<<","<<fname<<endl<<"Grade:"   <<grade<<endl<<"Age:"<<age<<endl;  
  20.    system("pause");  
  21.    return(0);  
  22. }  
 

 

 

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

 

example 2:

[cpp]  view plain copy
  1. //《C++ primary plus》第四章编程练习题1  
  2. #include <iostream>  
  3. using namespace std;  
  4. char fname[5];  
  5. char lname[5];  
  6. char grade;  
  7. int age;  
  8. int main()  
  9. {  
  10.     cout<<"What is your first name?";  
  11.     cin.getline(fname,5);  
  12.     cout<<"What is your last name?";  
  13.     cin.getline(lname,5);  
  14.     cout<<"What letter grade do you deserve?";  
  15.     cin>>grade;  
  16.     cout<<"What is your age?";  
  17.     cin>>age;  
  18.     cout<<"Name:"<<lname<<","<<fname<<endl<<"Grade:"<<grade<<endl<<"Age:"<<age<<endl;  
  19.     system("pause");  
  20.     return(0);  
  21. }  

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