By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,804 Members | 1,634 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,804 IT Pros & Developers. It's quick & easy.

STL string class and Number conversion

P: n/a
Hi all!

Do you know if there's a native C++ way to convert an STL string containing
a number into a real "int" or "float" number?
Is quite not comfortable to use "itoa" or "atoi" or the sscanf/sprintf
function.

Bye and thanks!
Alex
Jul 23 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a

"Alessandro Monopoli" <te*******@ammaza.com> wrote in message
news:hd***********************@news4.tin.it...
Hi all!

Do you know if there's a native C++ way to convert an STL string
containing a number into a real "int" or "float" number?
Is quite not comfortable to use "itoa" or "atoi" or the sscanf/sprintf
function.

Bye and thanks!
Alex


Look at the stringstream class. (Perhaps it's istringstream? I forget.)

-Howard
Jul 23 '05 #2

P: n/a

"Alessandro Monopoli" <te*******@ammaza.com> wrote in message
news:hd***********************@news4.tin.it...
Hi all!

Do you know if there's a native C++ way to convert an STL string
containing a number into a real "int" or "float" number?
Is quite not comfortable to use "itoa" or "atoi"
The more robust alternative to 'atoi()' (there's no
'itoa()' in standard C++) is 'strtol()', declared
by <cstdlib> (or <stdlib.h>).

std::string s("123");
int value(0);
char **ep = 0;
value = std::strtol(s.c_str(), &ep, 10);
or the sscanf/sprintf


The 'C++' alternative to 'sscanf()' is a
'std::istringstream' object and the '>>'
operator. 'std::istringstream' is declared
by <sstream>.

std::string s("123");
int value(0);
std::istringstream iss(s);

if(!(iss >> value))
std::cout << "could not convert\n";
else
std::cout << value;

See your implementation's documentation and/or
a C++ text for details.

-Mike
Jul 23 '05 #3

P: n/a
Alessandro Monopoli wrote:
Hi all!

Do you know if there's a native C++ way to convert an STL string containing a number into a real "int" or "float" number?


Boost offers an implementation, using only native C++. Look for
boost::lexical_cast< T >.

I.e.
int i = boost::lexical_cast<int>( "5" );

HTH,
Michiel Salters

Jul 23 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.