C++ Primer Plus编程练习4.13 第2题 getline输入数据给string
题目:
2.修改程序清单4.4,使用C++ string类而不是char数组。
【补充】程序清单如下:
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout<<"Enter your name:\n";
cin.getline(name,ArSize);
cout<<"Enter your favorite dessert:\n";
cin.getline(dessert,ArSize);
cout<<"I have sone delicious " << dessert;
cout<<" for you, "<<name<<".\n";
return 0;
}
答案:书上无答案。
C++技术网辅导详解解答:
参考代码:
#include <iostream>
#include <string>
int main()
{
using namespace std;
string name,dessert;
cout << "Enter your name:\n";
getline(cin, name);
cout << "Enter your favorite dessert:\n";
getline(cin, dessert);
cout << "I have sone delicious " << dessert;
cout << " for you, " << name << ".\n";
return 0;
}
getline函数的原型如下:
istream& getline(istream& is, string& str, char delim);第一个参数是输入流对象,标准输入即从键盘输入,我们要使用cin对象,所以第一个参数是cin。第二个参数是用于接收数据的对象,也就是我们从char数组改之后的string对象。
istream& getline(istream& is, string& str);
我们这里不涉及到分隔符,所以使用第二个原型。其他的也就没有什么要说的。