Does anyone have a good method?

Recommended Answers

All 3 Replies

My preferred method is to use stringstream. As in:

#include <iostream>
#include <sstream>

using namespace std;

int main() {
  stringstream ss1("42");
  int value;
  ss1 >> value;          // convert string to int
  cout << value << endl;

  stringstream ss2;
  ss2 << value;          // convert int to string
  cout << ss2.str() << endl;

  return 0;
};

Otherwise, you can use the atoi / itoa functions, or the sscanf / sprintf functions.

If you're OK using external libraries, then boost has boost::lexical_cast, which can be used to do these conversions:

std::string s1( "123" );
int i = boost::lexical_cast< int >( s1 );

std::string s2 = boost::lexical_cast< std::string >( i );

If it can't do the conversion, lexical_cast throws a boost::bad_lexical_cast exception.

I believe that, internally, lexical_cast basically uses the stringstream method that Mike_2000_17 mentioned above.

I'll go aswell with the stringstream methods. It's form the standard libraries, and it's not that hard to implement. Have a look at the link that mike_2000_17 posted, you'll find everything you need there.
If you fancy, you can use the istringstream (which manipulates strings as input streams) or/with ostringstream (which manipulate strings as is they were output streams) but basically stringstream acts both as istringstreams and ostringstreams, but if you need only to work with input streams, or outpustreams, perhaps i/ostringstreams would suite you better.

#include <sstream>
#include <iostream>
#include <string>
using namespace std;

int main(){
    int value;
    string value_s;
    istringstream get_int("42"); 
    get_int>>value; // string to int as input stream.
    ostringstream get_string;
    get_string<<value; //int to string as output stream
    value_s=get_string.str();
    cout<<"Int 42+5: "<<value+5<<endl;
    cout<<"String 42+\"yh\": "<<value_s+"yh";
    return (0);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.