string to int conversion

May 17, 2009 at 11:44am
Hi!

I used atoi from stdlib to manage this conversion ... something like this.
1
2
3
4
5
6
7
8
#include <string>
#include <cstdlib>
...
	int x[5];
	string s;
        ...
	x[i] = atoi(s.c_str());
	...


Is there a method from string class to do this ... could not find one?
Thanks
May 17, 2009 at 12:22pm
1
2
3
4
5
6
7
std::stringstream stream;
std::string str="12";
stream <<str;
int n;
if (!(stream >>n)){
    //could not convert
}
Last edited on May 17, 2009 at 12:22pm
May 17, 2009 at 6:38pm
 
f3.cpp:5: error: aggregate ‘std::stringstream stream’ has incomplete type and cannot be defined


Why do i get this error?

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
using namespace std;
int main(){
	std::stringstream stream;
	std::string str="12";
	stream <<str;
	int n;
	if (!(stream >>n)){
		//could not convert
	}
}

May 17, 2009 at 8:21pm
#include <sstream>
May 17, 2009 at 10:31pm
Thanks
May 18, 2009 at 12:04pm
also

1
2
3
#include <boost/lexical_cast.hpp>

int n = boost::lexical_cast<int>( str );


does essentially the same thing, but in one line of code instead of three.
Topic archived. No new replies allowed.