Skip to main content
GameDev.net gamedev.net
🔒 Locked

converting string into other types help

Started by 3dmodelerguy Feb 23, 2005 at 10:29 PM 6 replies 1k views
Original Post
3dmodelerguy
3dmodelerguy
i want to bew able to convert my string into the following types: int float double i tried to google but could not find much help. any info or link would help, thanks.
mike25025
mike25025
atoi and atof
dont know how to get a double
Prototype
Prototype
Here's a generic one I often use:

template<typename TYPE>TYPE& StrConvert(const std::string& pStr){	static TYPE t;	std::stringstream _ss;	_ss << pStr;	_ss >> t;	return t;}


Example:
std::string test("3.14");std::cout << StrConvert<float>(test);

Washu
Washu
You could also use the old favorite (and boost::lexical_cast is roughly the same)

template<typename R, typename T>R lexical_cast(T const& t) {  R ret;  std::stringstream st;  if(!(st<<t) || !(st>>ret))    throw std::bad_cast();  return ret;}


Same idea as the previous poster, except that it can more than convert from just strings :P
In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.
3dmodelerguy
3dmodelerguy
when i use the atof i get a warning about converting double to float, why does atof return a double and not a float?
3dmodelerguy
3dmodelerguy
plus is there any why to convert string to bool and any function that converts directly to float?
Couvillion
Couvillion
Quote:
Original post by 3dmodelerguy
plus is there any why to convert string to bool and any function that converts directly to float?


Here's how you convert to bool:

bool boolFromString(string const &s){  //"true", "True", "TRUE", "T" or "t" treated as true, anything else as false  return s == "true" || s == "True" || s == "TRUE" || s == "T" || s == "t";}


Don't be afraid to do the obvious.

~~C--O -

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.