Substring Issue

I have a code that takes your birthdate in the format YYYYMMDD and break it up into MM DD YYYY but I'm getting some issues.

Here is my code:


[code=cpp]#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Enter your date of birth: (YYYYMMDD)" << endl;
string dateofBirth("0");
cin >> dateofBirth;

string year = dateofBirth.substr( 0, 4 );
string month = dateofBirth.substr( 4, 6 );
string day = dateofBirth.substr( 6, 8 );



cout << "You were born on... \n\n\n";
cout << "************************************" << endl;
cout << month + " " + day + " " + year;
cout << endl << endl << endl;
system("PAUSE");
}[/code]

Here is the output:


1
2
3
4
5
6
7
8
Enter your date of birth: (YYYYMMDD)
19951018
You were born on...

*************************************
1018 18 1995

Press any key to continue . . .


The 1018 18 1995 should be 10 18 1995.

What am I doing wrong?

You should use:

1
2
3
string year = dateofBirth.substr( 0, 4 );
string month = dateofBirth.substr( 4, 2 );
string day = dateofBirth.substr( 6, 2 );


since the second argument is length, not the end of string
Last edited on
Ahh, thanks. Wrong arguments. :P

EDIT: This is my current code, I'm trying to change the numbers to words, but I'm getting several errors. What's wrong?
[code=cpp]#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Enter your date of birth: (YYYYMMDD)" << endl;
string dateofBirth("0");
cin >> dateofBirth;

string year = dateofBirth.substr( 0, 4 );
string month = dateofBirth.substr( 4, 2 );
string day = dateofBirth.substr( 6, 2 );

if( month == '1' )
{
month = "January";
}
else if( month == '2' )
{
month = "Feburary";
}

//etc...

cout << "You were born on... \n\n\n";
cout << "************************************" << endl;
cout << month + " " + day + ", " + year;
cout << endl << endl << endl;
system("PAUSE");
}[/code]

Last edited on
Ok, well I noticed several errors...first of all, the ' ' around a symbol tells the compilier it is a character, use "" for a string. Secondly, if they put it in the format you tell them to, you will be getting lots of errors, since "01" != "1"...you are probably trying to do:

1
2
3
4
if( month == "01")
{
   month = "January";
} //... 
Topic archived. No new replies allowed.