Converting Strings

D

Daniel Moree

ok, i've got my file reader working just the way i need.
Thanks to everyones help, i can convert basic strings to cstrings. But,
i need a little more help.

Got a way of converting a string or cstring into a number? once i can do
this, i'll be done. I'm good at doing any thing else that i need to in a
c/c++ program. Just never have done file stuff before.

Again, thanks for any help you provide.

Daniel Moree
 
K

Kai-Uwe Bux

Daniel said:
ok, i've got my file reader working just the way i need.
Thanks to everyones help, i can convert basic strings to cstrings. But,
i need a little more help.

Got a way of converting a string or cstring into a number? once i can do
this, i'll be done. I'm good at doing any thing else that i need to in a
c/c++ program. Just never have done file stuff before.

Again, thanks for any help you provide.

Daniel Moree

Have a look at boost::lexical_cast.

More down to earth: string-streams from <sstream> are your friend.

#include<sstream>

template< typename T >
T string_to_any ( const std::string & str ) {
T result;
std::stringstream dummy ( str );
if ( !( dummy >> result ) ) {
throw( std::runtime_error( "conversion from string failed" ) );
}
return( result );
}

template< typename T >
std::string any_to_string ( const T & obj ) {
std::stringstream dummy;
if ( !( dummy << obj ) ) {
throw( std::runtime_error( "conversion to string failed" ) );
}
return dummy.str();
}



Use like

double x = string_to_any< double >( "0.4" );



Best

Kai-Uwe Bux
 
J

Jay Nabonne

ok, i've got my file reader working just the way i need.
Thanks to everyones help, i can convert basic strings to cstrings. But,
i need a little more help.

Got a way of converting a string or cstring into a number? once i can do
this, i'll be done. I'm good at doing any thing else that i need to in a
c/c++ program. Just never have done file stuff before.

Again, thanks for any help you provide.

Daniel Moree

If by "number" you mean "integer", then check out atoi().

- Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top