In the brush some topics, always encounter strings and numbers to transform the problem, today we are in C + + to use a variety of methods to achieve. Sample code uploaded to Https://github.com/chenyufeng1991/TransferStringAndInt.
(1) string-> char *
String-> char *
string str3 = "Chenyufeng";
const char *str3tochar;
Str3tochar = Str3.c_str ();
In C + + string We commonly use <STRING> in STL, and in C language we often use character arrays. Use STRING.C_STR () directly to convert a string to char *;
(2) char *-> string
char *-> string
char *str4 = "Yufeng";
String STR5 (STR4);
cout << STR5 << Endl;
You can complete the operation of initializing a string using char * using the constructor in string directly.
(3) using Ostringstream to convert numbers to string
You can enter an int into the stream using Ostringstream and then convert to a string;
ostringstream os;//string output stream
int i = 123;
Os << "Hello" << i;
cout << os.str () << Endl;
Os << i;
cout << os.str () << Endl;
OS << "World";
cout << os.str () << Endl;
Ostringstream is actually an output stream of strings that can be constantly inserted into the stream. Then call the Str () method in Ostringstream to convert the data in the stream to string.
(4) using Istringstream to convert strings to numbers
Read a string with the Istringstream object
Istringstream is;//String input stream
is.str ("567");
Int J;
is >> J;
cout << J << Endl;
(5) Atoi: library function, char * converted to int
String-->int
//Note: atoi () can only pass the const char type, so you need to convert string to const char
string str = "789";
int str2int = atoi (Str.c_str ());
cout << str2int << Endl;
Note that the parameters in Atoi pass a char *, not a string.
(6) Sprintf:int converted to char *
The ITOA function cannot be used in Int-->srting,xcode because it is not defined in standard C + +, but it is available in some compilers, so it is recommended to use sprintf
char eeeee[10];
sprintf (eeeee, "%d", 444);
cout << String (eeeee) << Endl;
Note that the first parameter of sprintf is to pass a character array or a character pointer. The second parameter is formatted, and "%d" represents an int.
In fact, the most convenient is the use of itoa, you can directly for the conversion of int and char *, because I am using Xcode programming, in the Xcode can not use the Itoa function, because itoa this function is not included in the C + + standard library. So I can only use sprintf here. We can go and try itoa.