C++ primer 第五版 第五章编程练习节选(结构运算)

本文介绍了一个使用C++实现的动态数组管理结构体实例,通过读取和存储汽车制造商信息及生产年份,展示了如何创建、读取、遍历和释放结构体数组的空间。代码中使用了标准输入输出流、字符串操作以及动态内存管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Practice makes Pefect.!

#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;
}

记录,让学习充满活力!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值