本文提供了C++ Primer Plus第六版中4.13节的编程练习详解,包括使用C++ string类替换char数组、结合姓名、初始化CandyBar结构、动态分配内存以及处理数组和结构数据等实战示例。
摘要由CSDN通过智能技术生成
4.13编程练习
1.编写一个C++程序,如下述输出示例所示的那样请求并显示信息:
What is your first name? Beety Sue What is your last name? Yewe What letter grade do you deserve? B What is your age? 22 Name: Yewe, Betty Sue Grade: C Age: 22 注意,该程序应该接受的名字包含多个单词。另外,程序将向下调整成绩,即向上调一个字母。假设用户请求A、B或C,所以不必担心D和F之间的空档。
#include <iostream>#include <string>usingnamespacestd;
int main(){
string First, Last;
char grade;
int age;
cout << "What is your first name?";
getline(cin, First);
cout << "What is your last name?";
getline(cin, Last);
cout << "What letter grade do you deserve?";
cin >> grade;
cout << "What is your age?";
cin >> age;
cout << "Name: " << Last << "," << First << endl;
cout << "Grade: " << char(grade + 1) << endl;
cout << "Age: " << age << endl;
system("pause");
return0;
}
2. 修改程序清单4.4,使用C++ string类而不是char数组。
#include <iostream>#include <string>usingnamespacestd;
int main(){
string s1, s2;
cout << "Enter your name:" << endl;
getline(cin, s1);
cout << "Enter your favorite dessert:" <<