// 编程练习 04.01_display message_2.cpp
/***************************************************************
1.编写一个C++程序,如下述输出范例所示的那样请求并显示信息:
What is your first name? Betty Sue
What is your last name? Yew
What letter grade do you deserve? B
What is your age? 22
Name: Yew, Betty Sue
Grade: C
注意,该程序应该接受的名字包含多个单词。另外,程序将向下调整成绩,即向上调一个字母。
假设用户请求A、B或C,所以不必担心D和F之间的空档。
********************************************************************************************/
#include <iostream> // a preprocessor directive
#include <string> // for enter the name
using namespace std;
struct message
{
char *FirstName;
char *LastName;
char Grade;
int age;
};
/*有错,连对象都还没有定义
int main()
{
string temp;
cout << "What is your first name? ";
cin >> temp;
message.FirstName = new char [strlen(temp) + 1];
strcpy(message.FirstName, temp);
cout << "What is your last name? ";
cin >> temp;
message.LastName = new char [strlen(temp) + 1];
strcpy(message.LastName, temp);
cout << "What letter grade do you deserve? ";
cin.get();
cin.get(message.Grade);
cout << "What is your age? ";
cin >> message.age;
cout << "Name: " << message.*LastName << ", " << message.*FirstName;
cout << endl << "Grade: " << ((char)(message.Grade + 1)) << endl;
cin.get();
return 0;
}
***/
/*************************************************************************
打算参考书上的
char *ps;
ps = new char[strlen(animal) + 1];
strcpy(ps, animal);
谁知道呢?挺多错误的。
G:\Temp\编程练习_04.01_display message_2.cpp:43: error: `LastName' undeclared (first use this function)
G:\Temp\编程练习_04.01_display message_2.cpp:43: error: (Each undeclared identifier is reported only once for each function it appears in.)
G:\Temp\编程练习_04.01_display message_2.cpp:43: error: expected primary-expression before '.*' token
************************************************************************/
int main()
{
string temp;
cout << "What is your first name? ";
cin >> temp;
message msg;
msg.FirstName = new char [strlen(temp.c_str()) + 1]; // string 类型获取长度方法 strlen(string.c_str())
strcpy(msg.FirstName, temp.c_str());
cout << "What is your last name? ";
cin >> temp;
msg.LastName = new char [strlen(temp.c_str()) + 1];
strcpy(msg.LastName, temp.c_str());
cout << "What letter grade do you deserve? ";
cin.get();
cin.get(msg.Grade);
cout << "What is your age? ";
cin >> msg.age;
cout << "Name: " << msg.LastName << ", " << msg.FirstName;
cout << endl << "Grade: " << ((char)(msg.Grade + 1)) << endl;
cin.get();
return 0;
}
(2011.07.06)C++ 结构体中字符指针在main中使用new的赋值问题。
最新推荐文章于 2023-08-01 20:08:21 发布