C ++从字符串计算年龄

时间:2014-04-02 14:08:27

标签: c++

我是C ++的新手,我需要在我的程序中包含一个函数来计算学校代码中某人的年龄,如下所示:MAPA29088809 年龄是28/08/88 ...... 我想我需要使用子串或其他东西,但我不知道如何开始......有人可以帮我吗?

我所拥有的只是一种从给定年龄来计算它的方法......

int main()
{
    system("TITLE how old are you?");
    int yearnow,yearthen,monthnow,monththen,age1,age2;
    cout<<"\t\t\tEnter the current year and month \n\t\t\t(eg. 1997, enter,7,enter):\n";
    cin>>yearnow;
    cin>>monthnow;
    cout<<"Enter your birthyear and month: \n";
    cin>>yearthen;
    cin>>monththen;
    if(monththen >12 || monththen<1)
        return 1;
    if(monththen > monthnow){
         age1=yearnow-yearthen-1;
         age2=(12-monththen) + monthnow;
    }else{
         age1=yearnow-yearthen;
         age2=12-monththen;
    }
    cout<<"\n\n\t\t\tYou are "<<age1<<" year and "<<age2<<" moth old";
    system("pause>>void");
}

2 个答案:

答案 0 :(得分:1)

这是一个相当简单的问题。您有一个包含有价值信息对的字符串。

char* inputData = "MAPA29088809";

假设前四个字符是如何解析此数据的标识符:

char* format = new char[5]; // Extra character for the null terminator
memset( format, 0, 5 );
memcpy( format, inputData, 4 );

if( strcmp( format, "MAPA" ) == 0 ) // then your input data is in MAPA format

然后,对于其他数据,基于给定的格式,可以相当容易地拉出来。

char* day = new char[3];
memset( day, 0, 3 );
memcpy( day, format + 4, 2 );

char* month = new char[3];
memset( month, 0, 3 );
memcpy( month, format + 6, 2 );

char* year = new char[3];
memset( year, 0, 3 );
memcpy( year, format + 8, 2 );

char* whateverThatLastOneIs = new char[3];
memset( whateverThatLastOneIs, 0, 3 );
memcpy( whateverThatLastOneIs, format + 10, 2 );

您可以使用atoi将它们转换为整数。

int iDay = atoi(day);
int iMonth = atoi(month);
int iYear = atoi(year);
int iWhatever = atoi(whateverThatLastOneIs);

这是一种快速而肮脏的方法。使用std :: string和substr可能会更好。但这基本上就是你想要的。

答案 1 :(得分:0)

您可以使用std::string的{​​{3}}方法将年,月和日提取为字符串。然后,您可以使用substr(或atoi,如果您有权访问C ++ 11编译器)将字符串转换为整数。