C++基本データ型変換

8190 ワード

コード:
#include 
#include 
#include 

/*
      :2018.06.28
        
*/
#define CHAR_TO_INT(x)  int((x) - '0')
void Show(char *p);
void ShowString(std::string &p);
int StrToInt(const std::string &p);
int main()
{
    using namespace std;
    /*              */
    char        temp;
    char        t[10]           = {0};
    char *      p               = NULL;
    string      str             = "";
    int         mInt            = 0;
    double      mDouble         = 0.0;  
    __int64     mInt64          = 0;

    /*  string      char*   */
    str = "123456";
    p = (char *)str.c_str();
    Show(p);
    str = "789";
    p = (char *)str.data();
    Show(p);
    str = "456";
    str.copy(p,str.length(),0);
    Show(p);
    str = "";

    /*   char*      string  */
    p = "123";
    str = p;
    ShowString(str);
    p = NULL;

    /*  string      char[]  */
    str = "456789";
    //str.data()    str    
    //                          
    strcpy(t,str.data());   
    Show(t);
    memset(t,0,sizeof(t));
    str = "";
    str = "123456";
    int i = 0;
    for (; i < str.length(); i++)
    {
        t[i] = str[i];
    }
    if ( i < sizeof(t))
    {
        t[i+1] = '\0';  //          ‘\0’  
    }
    memset(t,0,sizeof(t));
    str = "";

    /* string     int  double int64 */
    str = "123";
    mInt     = atoi(str.c_str());
    mDouble  = atof(str.c_str());
    mInt64   = _atoi64(str.c_str());
    printf(" int = %d, double = %f, int64 = %llu
"
,mInt,mDouble,mInt64); str = ""; str = "456"; mInt = stoi(str); mDouble = stod(str); /* string to_string(val) val string stoi(str,pos,b) str p int stol(str,pos,b) long stoul(str,pos,b) unsigned long stoll(str,pos,b) long long stoull(str,pos,b) unsigned long long stof(str,pos) float stod(str,pos) double stold(str,pos) long double */ printf(" int = %d, double = %f, int64 = %llu
"
,mInt,mDouble,mInt64); str = ""; // str = "123456789"; mInt = StrToInt(str); cout <<"StrToInt(str) = "<< mInt << endl; str.clear(); /* char int */ temp = '9'; cout << " CHAR_TO_INT = "<< CHAR_TO_INT(temp) << endl; /************* FINALLY *******/ delete p; p = NULL; system("pause"); return 0; } void Show(char *p) { std::cout << " char * = "; while (*p != NULL) { std::cout << *p << " "; p++; } std::cout << "
"
; } void ShowString(std::string &p) { std::cout << "string = "<< p.c_str() << std::endl; } int StrToInt(const std::string &p) { int i = 0,val = 0,strLenth = p.length(); // if ( p[0] == ' - ' ) i = 1 ; // while (i < strLenth) { //p[i] - ' 0 ' = ASCII val = val * 10 + ( int )(p[i] - '0'); i ++ ; } if (p[ 0 ] == ' - ' ) val *= - 1 ; return val; }

出力:///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////)=123456789 CHAR_TO_INT=9任意のキーを押して続行してください...
//////////////////////////////////////////////////////////////////////