converting numbers to text and vice versa is a common issue as it can be useful in many different...
TRANSCRIPT
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
1/19
Converting numbers to text and vice versa is a common issue as it can be useful in many differentsituations and C++ 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 someContents:
C++ - stringstreams Number to StringCustom FormattingString to Number Simple Sample FunctionsC++ - boost libraryC - stdioC - stdlibWriting your own function
C++ - stringstreams
The C++ stream library is powerful and it allows easy formatted input output operations. Withstringstreams 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
Number to String
Converting a number to a string takes two steps using stringstreams:
Outputting the value of the number to the streamGetting the string with the contents of the stream
As with this conversion needs only output operation with the stream, an ostringstream ( outputstring stream ) can be used instead of the stream for both input and output ( stringstream )
Here is an example which shows each step:
12345678910
11int Number = 123; // number to be converted to a string
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
2/19
string Result; // string which will contain the result
ostringstream convert; // stream used for the conversion
convert
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
3/19
5fatagosi
6
7891011
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
4/19
12anggaanggi13141516171819
2021222324252627282930
313233// Headers needed:
#include #include #include #include // this should be already included in
// Defining own numeric facet:
class WithComma: public numpunct // class for decimal numbers using comma instead of
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
5/19
point{
protected:char do_decimal_point() const { return ','; } // change the decimal separator
};
// Conversion code:
double Number = 0.12; // Number to convert to string
ostringstream Convert;
locale MyLocale( locale(), new WithComma);// Crate customized locale
Convert.imbue(MyLocale); // Imbue the custom locale to the stringstream
Convert
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
6/19
string Text = "456"; // string containing the number
int Result; //number which will contain the result
istringstream convert(Text); // stringstream used for the conversion constructed with the contents of 'Text'
// ie: the stream will start containing the characters of 'Text'
if ( !(convert >> Result) ) //give the value to 'Result' using the characters in the streamResult = 0; //if that fails set 'Result' to 0
//'Result' now equal to 456
This conversion is even easier to reduce to a single line:
123string Text = "456";
int Number;if ( ! (istringstream(Text) >> Number) ) Number = 0;
In the above code an object of istringstream gets constructed from 'Text' istringstream(Text) and itscontents 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 somemore 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:
12345
67template
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
7/19
string NumberToString ( T Number ){
ostringstream ss;ss > result ? result : 0;
}
Usage: StringToNumber ( 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
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
8/19
C++ - Boost Library
Using stringstreams is the standard C++ way of doing these conversions but they usually need a fewlines of code
Among the Boost libraries there is lexical_cast which allows to perform the stringstreamconversions through simple function callTo make this library working, just include the header, it doesn't need to be linked
12345678// Boost header needed:
#include
// Number to string conversion:
Text = boost::lexical_cast(Number); 45fatagosi// String to number conversion: Number = boost::lexical_cast(Text); The above examples don't handle eventual conversion failuresWhen boost::lexical_cast fails, it throws boost::bad_lexical_cast ( derived from std::bad_cast )
1
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
9/19
234567
891011try
{Number = boost::lexical_cast(Text);
}catch ( const boost::bad_lexical_cast &exc ) // conversion failed, exception thrown by lexical_castand caught{
Number = 0; // give 'Number' an arbitrary value ( in this case zero )// if you don't give it any value, it would maintain the value it had before the conversion
// A string containing a description of the exception can be found in exc.what()}
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 stdoutUsing this is not as easy as with streams as the format string changes depending on the type of thenumber which needs to be converted
Example:
12345int Number = 123; // number to convert
char Result[16]; // string which will contain the number
sprintf ( Result, "%d", Number ); // %d makes the result be a decimal integer
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
10/19
String to Number
As printf, also scanf has a related function which can read from a character array, sscanf 123
45char Text[] = "456"; // string to be converted
int Result; // number which will contain the result
sscanf ( Text, "%d", &Result );
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:
12345678char Text[] = "456"; // string to be converted
int Result; // number which will contain the result
int Succeeded = sscanf ( Text, "%d", &Result );
if ( !Succeeded || Succeeded == EOF ) // check if something went wrong during the conversionResult = 0;
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
11/19
C - stdlib
The stdlib header contains some functions to convert text and numbers Notice that some of these functions are not standard!These functions are:
itoa
atoiatolatof strtolstrtoulstrtod
- For examples refer to the individual reference pages -
Writing your own function
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
12/19
Using already existing libraries is easier and better but, just to show how some of the abovesolutions work, here are some examples of how to write functions to convert text to numbers andnumbers to text using only the core language
The following is the implementation of itoa found in the book "The C Programming Language"
12345678910111213141516/* itoa: convert n to characters in s */
void itoa(int n, char s[]){
int i, sign;
if ((sign = n) < 0) /* record sign */n = -n; /* make n positive */
i = 0;do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */} while ((n /= 10) > 0); /* delete it */if (sign < 0)
s[i++] = '-';s[i] = '\0';reverse(s);
}
The function reverse used in itoa is defined like this in the same book:
123456
789
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
13/19
101112/* reverse: reverse string s in place */
void reverse(char s[]){
int i, j;char c;
for (i = 0, j = strlen(s)-1; i
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
14/19
8910111213
14151617181920212223int atoi( char string[] )
{int sign = 0, // whether the number is negative
result = 0, // result of conversionposition = 0; // position in the string
if ( string[0] == '-' ) // check for minus{
position++; // skip this character when convertingsign = 1; // the number is negative
}
for ( ; string[position]; position++ ) // for each character in the ( \0 terminated ) string{
result *= 10; // move the digits by one positionresult += string[position] - '0'; // get the number
}
if ( sign ) // if the number was negativeresult *= -1; //change the sign
return result; // return the result
}
Of course these functions are bad for many reasons and should not be used in actual codeThey just show the idea behind the conversion between an integer value and a character sequence
Home page | Privacy policy
cplusplus.com, 2000-2009 - All rights reserved - v2.3Spotted an error? contact us
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
15/19
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
16/19
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
17/19
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
18/19
-
8/9/2019 Converting Numbers to Text and Vice Versa is a Common Issue as It Can Be Useful in Many Different Situations an
19/19