难道BCB这么麻烦?请看代码 - -!!

#pragma hdrstop
#include <vcl.h>
#include <iostream.h>
//---------------------------------------------------------------------------
#pragma argsused
struct Person
{
public:
    Person()
    {
        cout<<"哇~哇~"<<endl;
        cout<<"请你为新生儿取个名字:";
        getline(cin,name);
    }
    virtual ~Person()
    {
        cout<<"咳-咳,我离去了!"<<endl;
    }
    virtual void introduction()
    {
        cout<<"你好,我是:"<<getname()<<endl;
    }
    string getname()
    {
        return name;
    }
private:
    string name;
};
struct Beauty : public Person
{
    virtual ~Beauty()
    {
        cout<<"呜~呜~,我去了 - -!"<<endl;
    }
    virtual void introduction()
    {
        cout<<"Hi,我是美女:" <<getname()<<endl;
    }

};
int main(int argc, char* argv[])
{
    while(true)
    {
       
        cout<<"请选择您的类型:"<<endl;
        cout<<"1、普通人;"<<endl;
        cout<<"2、美女;"<<endl;
        cout<<"3、野兽;"<<endl;
        string temp1;
        AnsiString temp2;
        int temp;
        getline(cin,temp1);
        temp2=temp1.c_str();
        temp=StrToInt(temp2);

        if (temp==1)
        {
            Person *ptren=new Person;
            ptren->introduction();
            break;
        }
        else if (temp==2)
        {
            Person *meimei = new Beauty;
            meimei->introduction();
            break;
        }
        else
        {
            cout<<"你是野兽?请重新选择吧"<<endl;
            continue;
        }
    }
    getchar();
    return 0;
}

看到这:string temp1;
               AnsiString temp2;
               int temp;
              getline(cin,temp1);
              temp2=temp1.c_str();
              temp=StrToInt(temp2); 

     我惊呆了,难道就为了得到一个整型的变量,却转了两次类型。(初用BCB,所以很有可能是我不了解这个工具)对于它这里面的两种字符串类型很是感到不解。难道就没有什么函数能把String类型的直接转为Int么?

    上例子来源于南老师白话C++2008版,但由于我最早看的是05版,所以编译工具也是采用了05推荐的BCB。在08版中,南老师没有采用getline()函数,而是这样处理的:

        int sel = 0;
        cin >> sel;

        if
(cin.fail()) {
            cin.clear();
        }

        cin.sync();
   
    由于代码中涉及有在变量诞生时要求输入姓名,所以在输入完成后,一按回车[getchar()],系统就退出了。(BCB特点 -  -),所以我就无法看到结果是否正确,那么为了能够显示出我输入的姓名,于是没用cin>>sel 的办法,而调用了函数getline();这样就引发了上面的类型来回转换。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值