c++primerplus(第六版)课后编程练习答案 下载本文

. .

string name,dessert;

cout<<\ getline(cin,name);

cout<<\ getline(cin,dessert);

cout<<\ cout<<\ return 0; }

//有时候会遇到需要按下两次回车键才能正确的显示结果,这是vc++6.0的一个BUG,更改如下:else if (_Tr::eq((_E)_C, _D)) {_Chg = true;

_I.rdbuf()->sbumpc();//修改后的 break; }

ex4.3 输入其名和姓,并组合显示 #include #include const int Asize=20; int main() {

using namespace std; char fname[Asize]; char lname[Asize];

char fullname[2*Asize+1];

cout<<\输入名字,存储在fname[]数组中 cin.getline(fname,Asize);

cout<<\输入姓,存储在lname[]数组中 cin.getline(lname,Asize);

strncpy(fullname,lname,Asize);//把姓lname复制到fullname空数组中 strcat(fullname,\把“, ”附加到上述fullname尾部

strncat(fullname,fname,Asize);//把fname名字附加到上述fullname尾部 fullname[2*Asize]='\\0';//为防止字符型数组溢出,在数组结尾添加结束符

cout<<\显示组合结果

return 0; }

//ex4.4 使用string对象 存储、显示组合结果 #include #include int main()

word完美格式

. .

{

using namespace std;

string fname,lname,attach,fullname; cout<<\

getline(cin,fname);//note:将一行输入读取到string类对象中使用的是getline(cin,str)

//它没有使用句点表示法,所以不是类方法 cout<<\ getline(cin,lname); attach=\

fullname=lname+attach+fname;

cout<<\ return 0; }

//ex4.5 declare a struct and initialize it 声明结果并创建一个变量 #include const int Asize=20; struct CandyBar {

char brand[Asize]; double weight; int calory; };

int main() {

using namespace std;

CandyBar snack={\ cout<<\ cout<<\ cout<<\ cout<<\ return 0; }

//ex4.6 结构数组的声明及初始化 #include const int Asize=20; struct CandyBar {

char brand[Asize]; double weight; int calory;

word完美格式

. .

};

int main() {

using namespace std; CandyBar snack[3]={

{\ {\ {\ };

for(int i=0;i<3;i++)//利用for循环来显示snack变量的内容 {

cout<

<

return 0; }

//ex4.7 pizza披萨饼 #include #include const int Size=20; struct pizza//声明结构 {

char company[Size]; double diameter; double weight; };

int main() {

using namespace std;

pizza pie;//创建一个名为pie的结构变量

cout<<\ cin.getline(pie.company,Size);

cout<<\ cin>>pie.diameter;

cout<<\ cin>>pie.weight;

cout<<\

cout<<\ cout<<\ return 0; }

word完美格式

. .

//ex4.8 pizza pie 披萨饼 使用new创建动态结构 #include #include const int Size=20; struct pizza//声明结构 {

char company[Size]; double diameter; double weight; };

int main() {

using namespace std;

pizza *pie=new pizza;//使用new创建动态结构 cout<<\ cin>>pie->diameter;

cin.get();//读取下一个字符

cout<<\ cin.get(pie->company,Size);

cout<<\ cin>>pie->weight;

cout<<\ cout<<\

cout<<\ delete pie;//delete释放内存 return 0; }

//ex.4.9 使用new动态分配数组—方法1 #include #include using namespace std; struct CandyBar {

string brand; double weight; int calory; };

int main() {

CandyBar *snack= new CandyBar[3];

word完美格式