Section 16.6. Converting Between Numbers and Strings


16.6. Converting Between Numbers and Strings

The standard library provides a variety of functions to interpret a numeral string and return a numeric value. These functions are listed in Table 16-18. The numeral conversion functions differ both in their target types and in the string types they interpret. The functions for char strings are declared in the header stdlib.h, and those for wide strings in wchar.h.

Table 16-18. Conversion of numeral strings

Conversion

Functions in stdlib.h

Functions in wchar.h

String to int

atoi( )

 

String to long

atol( ), strtol( )

wcstol( )

String to unsigned long

strtoul( )

wcstoul( )

String to long long

atoll( ), strtoll( )

wcstoll( )

String to unsigned long long

strtoull( )

wcstoull( )

String to float

strtof( )

wcstof( )

String to double

atof( ), strtod( )

wcstod( )

String to long double

strtold( )

wcstold( )


The functions strtol( ), strtoll( ), and strtod( ) can be more practical to use than the corresponding functions atol( ), atoll( ), and atof( ), as they return the position of the next character in the source string after the character sequence that was interpreted as a numeral.

In addition to the functions listed in Table 16-18, you can also perform string-to-number conversions using one of the sscanf( ) functions with an appropriate format string. Similarly, you can use the sprintf( ) functions to perform the reverse conversion, generating a numeral string from a numeric argument. These functions are declared in the header stdio.h. Once again, the corresponding functions for wide strings are declared in the header wchar.h. Both sets of functions are listed in Table 16-19.

Table 16-19. Conversions between strings and numbers using format strings

Conversion

Functions in stdio.h

Functions in wchar.h

String to number

sscanf( ), vsscanf( )

swscanf( ), vswscanf( )

Number to string

sprintf( ), snprintf( ), vsprintf( ), vsnprintf( )

swprintf( ), vswprintf( )




C(c) In a Nutshell
C in a Nutshell (In a Nutshell (OReilly))
ISBN: 0596006977
EAN: 2147483647
Year: 2006
Pages: 473

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net