简体   繁体   中英

c++ Converting a std::string to int, double, etc WITHOUT using a char array

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_cast to 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:

std::stringstream ss;
int result;
ss << input;
ss >> result;

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" .

I really can't get what your pasted code is about, but in C++ the best way to convert string to integer or float is to use stringstream .

const char* str = "10 20.5";
std::stringstream ss(str);
int x;
float y;

ss >> x >> y;

There is a function atoi which you can use. This converts it to a character array, but you don't have to do the math involved with indexing the array in a for loop.

#include <stdlib.h>
...
String number = "1234";    
int value = atoi(number.c_str());
std::cout << number;
...

For the atoi nay sayers, hopefully he'll understand this >.>

#include <boost/lexical_cast.hpp>

try {
    int x = boost::lexical_cast<int>( "123" );
} catch( boost::bad_lexical_cast const& ) {
    std::cout << "Error: input string was not valid" << std::endl;
}

The best way is the most efficient way, I don't think you'll find a better alternative to this, or using a character array.

The standard string class already has a member function that gives you access to the internal character array, c_str(), so you can just pass this to one of the standard C library functions that parse integers, such as strtol():

string s = "1234";
long n = strtol(s.c_str(), 0, 10);

That's the simplest code if you already know the string is a valid integer and don't care about error checking. If you want full error checking you would do something like this:

char* end = 0;
errno = 0;
long n = strtol(s.c_str(), &end, 10);
if (end == 0 || *end == 0)
    throw invalid_argument("Not a number");
else if (errno == ERANGE)
    throw overflow_error("Number is out of range");
else if (errno != 0)
    throw invalid_argument("Not a number");

Alternatively you could use C++ streams if you want to avoid C style character arrays completely (or rather, hide them completely inside the classes):

istringstream in(s);
int n;
in >> n;

You could also use boost::lexical_cast, which does basically the same thing.

  • I recommend Boost.Lexical_Cast

  • Or see the upcoming Boost.Conversion

  • Can also be achieved using Boost.Spirit, but is somewhat more complex

See "The String Formatters of Manor Farm" article by Herb Sutter.

您可能需要查看atoi函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM