0
点赞
收藏
分享

微信扫一扫

【15分】E. 电话号码升位(拷贝构造函数)

慎壹 2022-04-24 阅读 121
c++算法

题目描述
定义一个电话号码类CTelNumber,包含1个字符指针数据成员,以及构造、析构、打印及拷贝构造函数。

字符指针是用于动态创建一个字符数组,然后保存外来输入的电话号码

构造函数的功能是为对象设置键盘输入的7位电话号码,

拷贝构造函数的功能是用原来7位号码的对象升位为8位号码对象,也就是说拷贝构造的对象是源对象的升级.电话升位的规则是原2、3、4开头的电话号码前面加8,原5、6、7、8开头的前面加2。

注意:合法的电话号码:1、长度为7位;2、电话号码的字符全部是数字字符;3、第一个字符只能是以下字符:2、3、4、5、6、7、8。与上述情况不符的输入均为非法

输入
测试数据的组数 t

第一个7位号码
第二个7位号码

输出
第一个号码升位后的号码
第二个号码升位后的号码

如果号码升级不成功,则输出报错信息,具体看示例

输入样例1

3
6545889
3335656
565655

输出样例1

26545889
83335656
Illegal phone number

代码

#include <iostream>
#include <cstring>
using namespace std;

class CTelNumber
{
private:
    char *tellnum;

public:
    CTelNumber(char *tell)
    {
        tellnum = new char[strlen(tell) + 1];
        strcpy(tellnum,tell);
    }

    CTelNumber(const CTelNumber &oldtell)
    {
        tellnum = new char[strlen(oldtell.tellnum) + 2];
        if(oldtell.tellnum[0] == '2' || oldtell.tellnum[0] == '3' || oldtell.tellnum[0] == '4')
        {
            tellnum[0] = '8';
        }
        else tellnum[0] = '2';
        strcpy(tellnum + 1,oldtell.tellnum);
    }

    void myprint() {cout << tellnum << endl;}

    ~CTelNumber() {delete []tellnum;}
};

bool check(char *tell)
{
    if(strlen(tell) != 7) return false;
    if(tell[0] == '0' || tell[0] == '1' || tell[0] == '9') return false;
    for(int i = 0;i < strlen(tell);i ++)
    {
        if(!isdigit(tell[i])) return false;
    }
    return true;
}

int main()
{
    int t;
    cin >> t;
    while(t --)
    {
       char tell[10];
       cin >> tell;
       if(!check(tell)) cout << "Illegal phone number" << endl;
       else
       {
            CTelNumber oldtell(tell);
            CTelNumber newtell(oldtell);
            newtell.myprint();
       }
    }
    return 0;
}
举报

相关推荐

0 条评论