C++中有两个getline函数,这两个函数分别定义在不同的头文件中。
1.getline()是定义在<string>中的一个行数,用于输入一行string,以enter结束。
函数原型:getline(cin,str);
cin:istream类的输入流对象
str:待输入的string对象
example 1:
- //《C++ primary plus》第四章编程练习题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 的一个成员函数,定义在<iostream>中,用于输入行指定size的字符串,以enter结束。若输入长度超出size,则不再接受后续的输入。
example 2:
- //《C++ primary plus》第四章编程练习题1
- #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);
- }