String to Integer

Pls need help, trying to convert a string to an integer
this is the sample function i'm using and just a simple test to implement it.

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int convert (const string& str) {
stringstream ss(str);
int n;
ss >> n;
return n;
}


int main(){
string sat = "23-";
string satt = "12";
convert(sat);
convert(satt);
int res = sat+satt;
cout <<res;
}

int foo = atoi(satt.c_str());
Last edited on
thanks a lot, working now, i tried the atoi() earlier but it required char input. Thanks again.
Yeah, you need to convert the string to a char by uses c_str()
Another alternative, if you use Boost:
1
2
3
#include <boost/lexical_cast.hpp>
//...
int n = lexical_cast< int >( "10" );
There is nothing wrong with your int convert (const string& str) function, although it is not used correctly in main() (the returned value is not assigned to anything).

As another modern alternative, int foo = stoi(satt);
Last edited on
Topic archived. No new replies allowed.