• Register
36,800 points
11 5 4

Since the standard C++11, string-to-number conversions and vice versa are built into the standard library. All of the following functions are present in <string> (according to clause 21.5).

  • From line to number:

float              stof(const string& str, size_t *idx = 0);
double             stod(const string& str, size_t *idx = 0);
long double        stold(const string& str, size_t *idx = 0);
int                stoi(const string& str, size_t *idx = 0, int base = 10);
long               stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long      stoul(const string& str, size_t *idx = 0, int base = 10);
long long          stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);

They each take a string as input and try to convert it to a number. If it was not possible to build a valid number, for example, because there is no numeric data or an out-of-range number for the given type, an exception ( std::invalid_argument or std::out_of_range) is thrown .

If the conversion is successful and is idx not 0, it idx will contain the index of the first character that was not used for decoding. It can be an index after the last character.

Finally, integer types allow you to specify a base; numbers greater than 9 assume the alphabet (from a=10 to z=35). You can find additional information on the exact formatting that can be analyzed here for the numbers with floating point, integer signed numbers and whole numbers without sign.

Finally, for every function, there is also an overload that takes std::wstring as the first parameter.

  • From numeric to string:

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

They are simpler, you pass in the appropriate numeric type and you get the string back. For formatting options, you should go back to the C ++ 03 stringsream option and use stream manipulators as described in another answer here.

As noted in the comments, these functions fall back to the default mantissa precision, which is probably not the maximum precision. If your application requires more precision, it is best to revert to other string formatting procedures as well.

There are also similar functions defined with a name to_wstring, they will return a value std::wstring.

36,800 points
11 5 4