String: How to convert digital types to strings

zhaozj2021-02-16  51

String: How to convert digital types to strings

Old C method (disapproval)

Code: ------------------------------------------------ -------------------------------- CHAR * C [10]; // is complete enough - don't forgetting / 0 'Reserved extra bytes INT i = 1234; Sprintf (C, "% D", I); ------------------------ -------------------------------------------------- --------

See Sprintf () in MSDN in MSDN

Use cstring

Code: ------------------------------------------------ ------------------------------- I = 1234; cstring cs; cs.format ("% d", i ); ------------------------------------------------ --------------------------------

This format descriptor is the same as sprintf (), see the CString document in MSDN - it is quite direct.

A warning: The mismatch of the format descriptor ("% D") and the actual passing parameters will result in the result of unforeseen results, which is the same for sprintf () and cstring: format ().

C method:

The following example shows a template function that uses standard C classes to complete this task

Code: ------------------------------------------------ -------------------------------- # include #include #include

Template std :: string to_string (t t, std :: ios_base & (* f) (std :: ostringstream OS; OSS << f << t; Return OSS.STR) }

INT main () {// to_string () The second parameter should be one of the following // std :: hex, std :: dec, and std :: oct std :: cout << to_string (123456, Std :: hex) << std :: endl; std :: cout << to_string (123456, std :: c) << std :: end1;}

/ * Output: 1e240361100 * / ------------------------------------------- -------------------------------------

This method is not only very chic, but also the type of security, because the compiler will select the appropriate std :: ostringstream :: Operator << ().

转载请注明原文地址:https://www.9cbs.com/read-24458.html

New Post(0)