[ create a new paste ] login | about

Link: http://codepad.org/iTsD6Xq3    [ raw code | fork ]

C++, pasted on Nov 25:
#ifndef STRINGCONVERSION_H
#define STRINGCONVERSION_H

#include "stdafx.h"
//#include <string>
//#include <boost/any.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>

class StringConversion
{
public:
	bool Convert(const std::string& str, int& out);
	bool Convert(const std::string& str, float* out);
	bool Convert(const std::string& str, double* out);
	bool Convert(const std::string& str, long* out);

private:
	
};


#endif

#include "stdafx.h"
#include "StringConversion.h"
#include <boost/lexical_cast.hpp>
#include <boost/any.hpp>


bool StringConversion::Convert(const std::string& str, int& out)
{
	try
	{
		out = boost::lexical_cast<int>(str);
		return true;
	}
	catch (boost::bad_lexical_cast &)
	{
		return false;
	}

}


bool StringConversion::Convert(const std::string& str, float* out)
{
	try
	{
		*out = boost::lexical_cast<float>(str);
		return true;
	}
	catch (boost::bad_lexical_cast &)
	{
		return false;
	}
}


bool StringConversion::Convert(const std::string& str, double* out)
{
	try
	{
		*out = boost::lexical_cast<double>(str);
		return true;
	}
	catch (boost::bad_lexical_cast &)
	{
		return false;
	}
}

//Usage


#include "stdafx.h"
#include <StringConversion.h>
//#include <string>

int _tmain(int argc, _TCHAR* argv[])
{
	StringConversion con;
	std::string strone = "12";
	std::string strtwo = "12.5";
	float * f = new float;
	int i = 0;

	bool done = false;
	
	if (con.Convert(strone, i))
		std::cout << i << std::endl;
	else if (con.Convert(strone, f))
		std::cout << *f << std::endl;
	
	delete f;
	return 0;
}


Create a new paste based on this one


Comments: