convert between std::string and int

Hi I don't what the best way to convert between std::string and int. Can someone please post the function they use.
Try to read this article: http://www.cplusplus.com/forum/articles/9645/
There I described the way I use and at the bottom of the 1st post are links to articles describing other ways
thanks
there are many ways to do it. I don't know exactly which one is the best for you, but i can tell that the fastest(?) one is
1
2
std::string myString = "45";
int value = atoi(myString.c_str()); //value = 45 


fastreams:
1
2
3
ifastream<basic_formatters, string_reader> myString(&string);
int value;
myString >> value;


this one should work too, but its surely slower than the 2 above:
1
2
3
4
5
6
7
8
#include <sstream>
#include <string>
using namespace std;

string myStream = "45";
istringstream buffer(myString);
int value;
buffer >> value;   // value = 45 
The stringstream way can be also used without having a named object:
1
2
3
string str = "123";
int numb;
istringstream ( str ) >> numb;
1
2
3
4
5
6
7
#include <boost/lexical_cast.hpp>

try {
    int x = boost::lexical_cast<int>( "123" );
} catch( boost::bad_lexical_cast const& ) {
    std::cout << "Error: input string was not valid" << std::endl;
}


Another C-like solution is strtol(), which is along the lines of atoi() except strtol() can
report conversion errors whereas in practice atoi() cannot.
Topic archived. No new replies allowed.