Feb 2, 2012 at 7:29pm UTC
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;
}
Feb 2, 2012 at 7:34pm UTC
int foo = atoi(satt.c_str());
Last edited on Feb 2, 2012 at 7:35pm UTC
Feb 2, 2012 at 7:49pm UTC
thanks a lot, working now, i tried the atoi() earlier but it required char input. Thanks again.
Feb 2, 2012 at 7:56pm UTC
Yeah, you need to convert the string to a char by uses c_str()
Feb 2, 2012 at 10:13pm UTC
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 Feb 2, 2012 at 10:13pm UTC