One of the big differences between c and c++ is that in c++ you can directly declare string variables by referring to the string header file, while in c you can only declare char s[n] to input a string. In this way, how the string type is converted to and from other types to facilitate our use becomes a relatively basic knowledge that we need to master.
1. Convert string type to array
Method 1:
Borrow the c_str() function encapsulated in the string class. (This function returns the first address of the string)
std::string s1;
const char* s;
s1 = "haohaoxeuxi";
s = s1.c_str();
std::cout<<s[0]<<std::endl;;
for(int i = 0; s[i] != '\0'; i++)
{
std::cout<<s[i];
}
The return value type of c_str() is of const char* type, and should be received in the same type.
Houji:
Use the strcopy() function to copy the string content into an array (the parameters of the strcpy() function are two addresses)
std::string s1;
char s[20];
s1 = "haohaoxuexi";
strcpy(s, s1.c_str());
std::cout<<s[0]<<std::endl;
for(int i = 0; s[i] != '\0'; i++)
{
std::cout<<s[i];
}
When using this method, be sure to reference the <cstring> header file
Method Three:
Convert string directly to array
std::string s;
s = "haohaoxuexi";
std::cout<<s[0]<<std::endl;
for(int i = 0; s[i] != '\0'; i++)
{
std::cout<<s[i];
}
In fact, it can be converted directly. . . .
2. Convert integer to string
Reference <sstream> header file
int a1 = 123456;
std::string s1;
std::stringstream ss;
ss << a1;
ss >> s1;
std::cout<<s1<<std::endl;
std::cout<<s1[1];
ss serves as an intermediate variable and can be implemented with data flow.