string to integer conversion

Apr 24, 2012 at 10:33am
I was trying to convert a string to integer but i am facing problem with it. I tried using atoi, strtol and stringstream. All the three methods are giving errors.
1. when i use atoi and strtol
string str="123";
long int num;
char temp[10];
num= strtol(str)

this is the error i get
"cannot convert 'std::string' to 'const char*' for argument '1' to 'long int strtol(const char*, char**, int)"

2. when i use stringstream
stringstream ss(str);
i get error "variable 'std::stringstream ss' has initializer but incomplete type"

Can someone help me find out the mistake?
Last edited on Apr 24, 2012 at 10:38am
Apr 24, 2012 at 11:21am
Hi nilagayu. I managed to find some flaws in your code and i fixed it and did a little test to show you that it has worked.
1
2
3
4
5
6
7
	char str[] = "123";
	long int num;
	num = strtol(str, NULL,10);

	int answer = num + 1;

	cout << num << " " << answer << endl;   


Now let me explain my code. You need to use char and not string. Firstly because the function strtol accepts only chars and not string, secondly you only gave one argument in the function when it needs three. The first argument which is str, This is which string you want to convert to a number, The second argument is only if you have multiple strings that you want to convert but because you don't have that i left it a NULL meaning no value and lastly is which base it is. The 10 just basically means base 10 and from my understanding i think base 10 is just the normal system we are using for instance every integer like 100 or 6 or 46 is a base 10 number.

Hope you understand my' ok' explanation of how to convert string to integer =). Oh and btw use code brackets etc [code] so it is easier to see the code. You can find how to do that on the right hand side under the header format.
Last edited on Apr 24, 2012 at 11:23am
Apr 24, 2012 at 12:33pm
Hi Sean. Thanks a lot for your explanation.
But is there any other way to convert a string to an integer other than to convert a char array to a integer. In my code i generate a string using the str.substr() function. I need to convert that string into a integer.

Apr 24, 2012 at 1:17pm
If your compiler is reasonably modern, you can use the C++ function stoi (or stol or stoll, depending on the desired integer type)

1
2
std::string str="123";
long int num = stol(str.substr(2,1));


demo: http://ideone.com/Ku7sS

Otherwise, stringstream can do it for you, just don't forget to #include <sstream>:

1
2
3
4
std::string str="123";
std::istringstream buf(str.substr(1,2));
long int num;
buf >> num;

demo: http://ideone.com/7wBBQ
Last edited on Apr 24, 2012 at 1:19pm
Apr 24, 2012 at 1:48pm
Thanks...
My compiler did not support stol. But i converted the string to char array using str.c_str().
Topic archived. No new replies allowed.