您的位置:首页 > 编程语言 > C语言/C++

C++学习(六)——类的学习—PhoneList对象数组程序示例

2016-10-30 21:05 399 查看
main.cpp

#include <fstream>
#include <string>
#include <iostream>
//#include <stdlib.h>
#include <cstdlib>
#include "PhoneList.h"
using namespace std;

#define FILE_IN "D:\\C++projects\\Book_Project\\9_5\\phonebook.txt"

int main(void)
{
PhoneList mylist[5];
ifstream Input;
Input.open(FILE_IN, ios::in);
if (!Input)
{
cout<<"文件不存在"<<endl;
exit(1);
}

int i, a, ex, num;
char buf[35];
for (i =0; i<5; ++i)
{
Input.getline(buf, 25);
mylist[i].SetName(buf);

Input.getline(buf, 30);
mylist[i].SetAddress(buf);

Input.getline(buf, 4);
a = atoi(buf);
Input.clear();
Input.getline(buf, 5);
ex = atoi(buf);
Input.clear();
Input.getline(buf, 7);
num = atoi(buf);
Input.clear();
mylist[i].SetPhone(a, ex, num);
}

cout.setf(ios::left);

cout<<"你的地址薄有下列信息:"<<endl;

for (i = 0; i<5; ++i)
{
mylist[i].ShowListing();
}
cout<<endl;
Input.close();
cout<<"bye"<<endl;

return 0;
}

PhoneList.h
#ifndef _PHONELIST_H_
#define _PHONELIST_H_

class PhoneList
{
public:
PhoneList();
void SetName(char n[]);
void SetAddress(char addr[]);
void SetPhone(int a, int e, int num);
void ShowListing();
private:
char name[25], address[30];
int areacode, exchange, number;
};

#endif // _PHONELIST_H_


PhoneList.cpp
#include "PhoneList.h"
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;

PhoneList::PhoneList()
{
name[0] = '\0';
address[0] = '\0';
areacode = 0;
exchange = 0;
number = 0;
}

void PhoneList::SetName(char n[])
{
strcpy(name, n);
}

void PhoneList::SetAddress(char addr[])
{
strcpy(address, addr);
}

void PhoneList::SetPhone(int a, int e, int num)
{
areacode = a;
exchange = e;
number = num;
}

void PhoneList::ShowListing()
{
cout<<endl<<setw(25)<<name<<setw(30)<<address;
cout<<areacode<<"-"<<exchange<<"-"<<number;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐