In C++ I have only seen this done by converting the string object into an array of characters. The tutorials with an array are a bit hard for me to understand. But I want to do the conversion without the array.
I do have an idea how to do it: the string is “1234”. After that I convert this text to an integer this way:
if (symol4 == "4") int_var += 4 * 1;
if (symol3 == "3") int_var += 3 * 10;
if (symol3 == "2") int_var += 2 * 100;
if (symol3 == "1") int_var += 1 * 1000; //Don't worry, I'm familiar with cycles, this code is only for explaining my algorithm
I hope you can understand the idea.
But I don’t know if this is the best way. I don’t know if there is a library that has a function that allows me to do that (I won’t be surprised if there is one).
I don’t know if not using a char array is a good idea. But that’s a different question that I’m going to ask later.
What’s the best way to convert a string to an integer, double, etc WITHOUT using an array of characters.
boost::lexical_castto the rescue:int result = boost::lexical_cast<int>(input)If you don’t want to rely on boost, you can use a stringstream, something like:
but that’s rather roundabout imo
And no don’t use
atoi– that function was flawed even back in C and it hasn’t gotten better with time. It returns 0 when an error happened while parsing – which has the obvious problem how you distinguish an error from parsing the string"0".