STL string class and Number conversion

  • Thread starter Alessandro Monopoli
  • Start date
A

Alessandro Monopoli

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
 
H

Howard

Alessandro Monopoli said:
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
 
M

Mike Wahler

Alessandro Monopoli said:
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
 
M

msalters

Alessandro said:
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
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top