Hello!

I've written a class called Date:

class Date {

     private:
      int day, month, year;

      public:
      Date();
      Date(const char *d);
      //other methods...
 };

I want to write a constructor that'll take as a parameter (as you can see) a c-string. That string will look like: "12022010". The first two characters refer to day, the next two characters refer to month and the last 4 characters refer to year. This means that string "12022010" means the 12th of February 2010. So the constructor will take its parameter in this form and give value to private members day, month and year. Does anyone have an idea how can i implement this thought? What comes to my mind is to split the c-string and then use atoi..but i think it's a bit messy thought (and time-consuming)..i want to find a smarter solution..:-/ Any thought will be appreciated..Thank you in advance for reading my post!

This is an example using string stream and c++ strings using a similar format to what you posted above.

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

class DATE
{
	int day, month, year;

	public:

	DATE();
	DATE(string d);
	int GetDay();
	int GetMonth();
	int GetYear();

};

DATE::DATE( string d )
{
	stringstream s(stringstream::in | stringstream::out); //set up string stream for input/output
	s << d.substr(0,2) << " " << d.substr(2,2) << " " << d.substr(4,4) << " "; //divide the string up and put it into the stream
	s >> day; //pull out day
	s >> month; //pull out month
	s >> year; //pull out year
}

int DATE::GetDay()
{
	return day;
}

int DATE::GetMonth()
{
	return month;
}

int DATE::GetYear()
{
	return year;
}


int main()
{
	DATE myDate("11122010"); //input date as string
	cout << myDate.GetDay() << "/" << myDate.GetMonth() << "/" << myDate.GetYear() << endl;

	return 0;
}

This is an example using string stream and c++ strings using a similar format to what you posted above.

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

class DATE
{
	int day, month, year;

	public:

	DATE();
	DATE(string d);
	int GetDay();
	int GetMonth();
	int GetYear();

};

DATE::DATE( string d )
{
	stringstream s(stringstream::in | stringstream::out); //set up string stream for input/output
	s << d.substr(0,2) << " " << d.substr(2,2) << " " << d.substr(4,4) << " "; //divide the string up and put it into the stream
	s >> day; //pull out day
	s >> month; //pull out month
	s >> year; //pull out year
}

int DATE::GetDay()
{
	return day;
}

int DATE::GetMonth()
{
	return month;
}

int DATE::GetYear()
{
	return year;
}


int main()
{
	DATE myDate("11122010"); //input date as string
	cout << myDate.GetDay() << "/" << myDate.GetMonth() << "/" << myDate.GetYear() << endl;

	return 0;
}

Thank you very much! I appreciate your instant answer! Cheers..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.