Conversion of C ++ basic types (numbers, characters, strings)

1. Conversion between integer and floating point

  (1) Common mandatory conversion, but there are problems

    double d_Temp;
    int i_Temp = 323;
    d_Temp = (double)i_Temp;

  (2) Use standard forced conversion

    For the time being, static_cast <type> (converted value); there are four standard mandatory types, which are not very specific.

    double d_Temp;
    int i_Temp = 323;
    d_Temp = static_cast<double>(i_Temp);

 

2. The conversion between strings and numbers, the most powerful is atoi

  (1) Use the sprintf_s function to convert the number into a string    

    int i_temp = 2020;
    std::string s_temp;
    char c_temp[20];
    sprintf_s(c_temp, "%d", i_temp);
    s_temp = c_temp;
    std::cout << s_temp << std::endl;

  (2) Use the sscanf function to convert the string to a number

    double i_temp;
    char c_temp[20] = "15.234";
    sscanf_s(c_temp, "%lf", &i_temp);
    std::cout << i_temp << std::endl;

  (3) atoi, atof, atol, atoll (C ++ 11 standard) function converts the string to int, double, long, long long type

    std::string s_temp;
    char c_temp[20] = "1234";
    int i_temp = atoi(c_temp);
    s_temp = c_temp;
    std::string s_temp;
    char c_temp[20] = "1234.1234";
    double i_temp = atof(c_temp);
    s_temp = c_temp;

  (4) strtol, strtod , strtof , strtoll, strtold  functions convert strings into int, double, float, long long, long double types

    std :: string s_temp;
     char c_temp [ 20 ] = " 4.1234 " ;
     double a = strtod (c_temp, nullptr);   // The following parameter is a reference to the string if a string is encountered

  (5) Use to_string to convert numbers into strings

    double d_temp = 1.567;
    std::string s_temp = to_string(d_temp);

3. Conversion between strings and characters

  (1) Convert char * from string with c_str

    string s_temp = "this is string";
    const char* c_temp;
    c_temp = s_temp.c_str();

  (2) The append function can be used to add characters one by one

    string s_temp;
    char c_temp[20];
    c_temp[0] = 'H';
    c_temp[1] = 'L';
    c_temp[2] = 'L';
    c_temp[3] = 'O';
    c_temp[4] = '\0';
    s_temp = c_temp;

 

Guess you like

Origin www.cnblogs.com/xiaodangxiansheng/p/12697278.html