#include "type_conversion.h"

#include <sstream>			// used by function String2Double()
using std::istringstream;	// used by function String2Double()
using std::stringstream;	// used by function Double2String(), Int2String()


CTypeConversion::CTypeConversion()
{
}

CTypeConversion::~CTypeConversion()
{
}

//---------------------------------------------------------------------
//                       CONVERTING FUNCTIONS
//---------------------------------------------------------------------

double CTypeConversion::String2Double(string &s)
{
	// function adopted from:
	// http://episteme.arstechnica.com/groupee/forums/a/tpc/f/6330927813/m/736000556631/p/2
	double d_return_value;
	istringstream iss(s);

	// Extract a double from the input string stream
	iss >> d_return_value;
	if (iss.fail())
	{
		return -9999.0;
	}

	return(d_return_value);
}

//---------------------------------------------------------------------

int CTypeConversion::String2Int(string &s)
{
	int i;
	sscanf(s.c_str(),"%d",&i);
	return(i);
}
//---------------------------------------------------------------------

string CTypeConversion::Double2String(double d)
{
	stringstream s;
	s << d;
	return(s.str());
}
//---------------------------------------------------------------------

string CTypeConversion::Float2String(float f)
{
	stringstream s;
	s << f;
	return(s.str());
}
//---------------------------------------------------------------------

string CTypeConversion::Int2String(int i)
{
	// Bjarne Stroustrup's C++ Style and Technique FAQ
	// http://www.research.att.com/~bs/bs_faq2.html#int-to-string
	stringstream s;
	s << i;
	return(s.str());
}
//---------------------------------------------------------------------


// Converting a date string 'YYYYMMDD' to three separate integer values
void CTypeConversion::Get_Date_Int(string date, int &year, int &month, int &day)
{
	// divide date string to year, month, and day string
	string y(date.c_str(),0,4);
	string m(date.c_str(),4,2);
	string d(date.c_str(),6,2);

	// convert strings to integer
	sscanf(y.c_str(),"%d",&year);
	sscanf(m.c_str(),"%d",&month);
	sscanf(d.c_str(),"%d",&day);
}