《C++ Primer 第五版编程练习 -- 第五章》

Practice make perfect.

  Chapter 5 exercise 6:

   problem description:

   设计一个名为car的结构,用它存储下述有关汽车的信息:生产商(存储在字符数组或string对象中的字符串)、生产年份(整数)。编写一个程序,向用户请问有多少辆汽车。随后,程序使用new关键字来创建一个由相应数量的car结构组成的动态数组。接下来程序提示输入每辆车的生产商(可由多个单词组成)和年份信息。请注意,这里需要特别小心,因为它将交替读取数值和字符串。最后,程序将显示每个结构的内容。

 

#include<iostream>
#include<string>    /*string I/O*/    

using namespace std;

struct Car
{
	string provider;
	int year;
};


int main()
{
	int total_num = 0;
	cout << "How many cars do you wish to catalog ? " ;
	cin >> total_num;
	/*allocate the dynamic struct*/
	Car* car = new Car[total_num];
	
	/*read I/O and save it*/
	for (int i = 0; i < total_num; ++i)
	{
		char ch;
		cout << "Car # "<< i+1 << endl;
		cout << "Please enter the provider : ";
		/*getchar() read Enter to exit, used for clearing the Enter input*/
		getchar();
		getline(cin, car[i].provider);
		cout << "Please enter the made year : " ;
		cin >> car[i].year;
	}
	
	/*traverse the struct*/
	cout << "Here is your collection : " << endl;
	for (int i = 0; i < total_num; ++i)
	{
		cout << car[i].year << " " <<car[i].provider << endl;
	}

	/*release the space*/
	delete[] car;
	return 0;
}

  

转载于:https://www.cnblogs.com/Welcome-Xwell/p/9751076.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值