int string and interconversions

A, string int turn way

The most original string, then the decimal arithmetic operations in accordance with the characteristics obtained int, but this approach too cumbersome, not described here.

Atoi standard library functions.

S = String "12 is";
int A = atoi (s.c_str ());
for other types also has a corresponding standard library functions, such as floating point atof (), long type atol () and the like.

Sstream stream object using a string defined in the header file to achieve the conversion.

istringstream is ( "12"); // configured stream input string, the content stream is initialized to "12" string
int i;
is >> i; // int read an integer stored in the stream is in the i

Two, int way to turn string

To_string standard library functions.

12 is I = int;
COUT the to_string << STD :: (I) << endl;
need not include any header, should be in the utility, but need not comprise, for direct use, but also re-define any other built-in type into the string upload function, it is convenient.

Sstream stream object using a string defined achieved.

ostringstream os; // output string configured a stream, the stream is empty
int i = 12 is;
OS << i; // int content output integer i to the output string stream
cout << os.str () << endl; // str using the stream function strings acquired content stream
str function strings for stream object and ostringstream istringstream apply, you can obtain the content stream.

Published 24 original articles · won praise 5 · Views 3955

Guess you like

Origin blog.csdn.net/qq_41345281/article/details/81583523