(2011.07.06)C++ 结构体中字符指针在main中使用new的赋值问题。

 
// 编程练习 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;
} 



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值