ref. http://www.cplusplus.com/articles/D9j2Nwbp/#stdio
Converting numbers to strings and strings to numbers
Score: 4.1/5 (645 votes)
Converting numbers to text and vice versa is a common issue as it can be useful in many different situations and C++98 doesn't provide a tool designed specifically to solve this problem.
Luckily C++ is a general purpose language so it allows to solve this quite easily and, as most things, you have many ways of accomplishing this task.
Here are listed some
With
To use
Here is an example which shows each step:
This operation can be shorten into a single line:
Here is constructed an unnamed stringstream object and performed the output
Stringstreams allow manipulators and locales to customize the result of these operations so you can easily change the format of the resulting string
Example: - This is not a complete program -
While a number can always be converted in a string, a string must be valid to be converted to a number ( eg: An attempt of converting
Here is the code example:
This conversion is even easier to reduce to a single line:
In the above code an object of istringstream gets constructed from 'Text'
If that operation fails
Locales and manipulators can be used as well as with any stream
A generic
Here are listed some functions to perform these conversion using stringstreams:
Usage:
Usage:
Notice: In the code examples std:: was omitted to make the code simpler
Using the last functions, there is no way of detecting whether the conversion succeded or failed
basic types to std::string objects and vice-versa.
std::to_string Converts basic numeric types to strings.
The set of functions
stoi, stol, stoll convert to integral types, the functions
stof, stod, stold to floating-point values.
These functions are declared in declared in <string>.
Note that since these functions were added in the latest version of the C++ standard,
they may not be available unless your implementation is very recent.
Among the Boost libraries there is
To make this library working, just include the header, it doesn't need to be linked
The above examples don't handle eventual conversion failures
When
In C there is no stream library, but the function
It works in a similar way to
Example:
As
If
Notice that some of these functions are not standard! These functions are:
- For examples refer to the individual reference pages -
Here is
Here is the function
This is easy to implement, here is an example:
As you can see, is possible to create a ( bad ) conversion function with just some basic C
The same applies to the opposite conversion:
Of course these functions are bad for many reasons and should not be used in actual code
They just show the idea behind the conversion between an integer value and a character sequence
Luckily C++ is a general purpose language so it allows to solve this quite easily and, as most things, you have many ways of accomplishing this task.
Here are listed some
Contents:
C++ - stringstreams
The C++ stream library is powerful and it allows easy formatted input output operations. With stringstreams you can perform this input/output to string, this allows you to convert numbers ( or any type with the<<
>>
stream operators overloaded ) to and from strings.With
stringstreams
you can use the same syntax to convert the different numeric types.To use
stringstreams
you need to #include <sstream>
Number to String
Converting a number to a string takes two steps using stringstreams:- Outputting the value of the number to the stream
- Getting the string with the contents of the stream
ostringstream
( output string stream ) can be used instead of the stream for both input and output ( stringstream
)Here is an example which shows each step:
|
|
This operation can be shorten into a single line:
|
|
ostringstream() << Number
Then, since the << returns a reference to an ostream
( a base of ostringstream
) the result of the operation needs to be casted back to a stringstream static_cast<ostringstream*>
Finally, we get the contents of the resulting stream as a string ->str()
and we assign that value to the string string String =
Custom formatting
Stringstreams allow manipulators and locales to customize the result of these operations so you can easily change the format of the resulting string
Example: - This is not a complete program -
|
|
String to Number
Also converting a string to a number via stringstream takes two steps:- Constructing the stream from the string
- Reading the value into the variable
istringstream
will be usedWhile a number can always be converted in a string, a string must be valid to be converted to a number ( eg: An attempt of converting
"hello"
to an integer would certainly fail ) so on this conversion, some checking must be doneHere is the code example:
|
|
This conversion is even easier to reduce to a single line:
|
|
istringstream(Text)
and its contents get read into the numeric variable >> Number
.If that operation fails
if ( !
, 'Number' is set to zero Number = 0;
Locales and manipulators can be used as well as with any stream
More complex cases
A generic
stringstream
( which could be used both for input and for output ) can be useful in some more complex situations and in almost any situation you need to perform operations not provided by string
Simple Sample Functions
Here are listed some functions to perform these conversion using stringstreams:
|
|
NumberToString ( Number );
|
|
StringToNumber<Type> ( String );
Notice: In the code examples std:: was omitted to make the code simpler
Using the last functions, there is no way of detecting whether the conversion succeded or failed
C++11
C++11 introduced some standard library functions that can directly convertbasic types to std::string objects and vice-versa.
std::to_string Converts basic numeric types to strings.
The set of functions
stoi, stol, stoll convert to integral types, the functions
stof, stod, stold to floating-point values.
These functions are declared in declared in <string>.
Note that since these functions were added in the latest version of the C++ standard,
they may not be available unless your implementation is very recent.
|
|
C++ - Boost Library
Using stringstreams is the standard C++ way of doing these conversions but they usually need a few lines of codeAmong the Boost libraries there is
lexical_cast
which allows to perform the stringstream conversions through simple function callTo make this library working, just include the header, it doesn't need to be linked
|
|
The above examples don't handle eventual conversion failures
When
boost::lexical_cast
fails, it throws boost::bad_lexical_cast
( derived from std::bad_cast
)
|
|
C - stdio
Number to String
In C there is no stream library, but the function
sprintf
can be used for conversionIt works in a similar way to
printf
but it will put the characters in a C string ( a character array ) instead of stdout
Using this is not as easy as with streams as the format string changes depending on the type of the number which needs to be convertedExample:
|
|
String to Number
As
printf
, also scanf
has a related function which can read from a character array, sscanf
|
|
If
sscanf
fails ( ie: the string is not a number ), the value of the variable passed remains unchanged, in that case the function should return zero as no argument were read successfully, if the string passed is so bad that nothing can be read from it, it would return EOF
:
|
|
C - stdlib
The stdlib header contains some functions to convert text and numbersNotice that some of these functions are not standard! These functions are:
- For examples refer to the individual reference pages -
Writing your own function
Using already existing libraries is easier and better but, just to show how some of the above solutions work, here are some examples of how to write functions to convert text to numbers and numbers to text using only the core language, the following examples are from the book "The C Programming Language"Here is
itoa
( Integer TO Alphabet )
|
|
Here is the function
reverse
used in itoa
:
|
|
reverse
uses the function strlen
from the header cstring ( string.h in C )This is easy to implement, here is an example:
|
|
As you can see, is possible to create a ( bad ) conversion function with just some basic C
The same applies to the opposite conversion:
|
|
Of course these functions are bad for many reasons and should not be used in actual code
They just show the idea behind the conversion between an integer value and a character sequence
Rate this
沒有留言:
張貼留言
有敘述錯誤或者是觀念有問題歡迎指正