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
long int num;
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
i get error "variable 'std::stringstream ss' has initializer but incomplete type"
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";
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.
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.