• 【C++】int、const char*、char*、char、string之间的转换


    #include "stdafx.h"
    #include<string>
    #include<vector>
    #include<iostream>
    #include<sstream>
    #include<stdio.h>
    #include<stdlib.h>
    
    
    using namespace std;
    
    //sstream
    string int2str1(int n){
        ostringstream oss;
        oss << n;
        string s = oss.str();
        return s;
    }
    
    //sprintf
    string int2str2(int n){
        char temp[64];
        sprintf_s(temp, "%d", n); 
        string str = temp;
        return str;
    }
    
    //sstream
    int str2int1(string s){
        int n;
        istringstream iss;
        iss.clear();
        iss.str(s);
        iss >> n;
        return n;
    }
    
    //sscanf
    int str2int2(string s){
        int n;
        sscanf_s(s.c_str(), "%d", &n);  //scanf前面加s用于把str输入到n中
        return n;
    }
    
    //stoi
    int str2int3(string s, int base){ // base:进制
        int n = stoi(s, nullptr, base);
        return n;
    }
    
    
    //c_str
    const char* str2Cchar(string s){
        //const char* ss = s.c_str(); //出错,因为s会被析构,ss指向垃圾内容
        char c[20];
        strcpy_s(c, s.c_str());
    
        return c;
    }
    
    //atoi
    int Cchar2int(const char* s){
        //char buffer[100];
        int n = atoi(s);
        return n;
    }
    
    char* int2char(int n){
        char buffer[100];
        _itoa_s(n, buffer, 10);
        return buffer;
    }
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        //cout << str2int1("1234") << endl;
        //cout << str2int2("1234") << endl;
        //cout << int2str1(1234) << endl;
        //cout << int2str1(1234) << endl;
    
        //string s1 = "123455";
        //const char* ss1 = str2Cchar(s1);
    
        //char s2[] = "123455";
        //const char* ss2 = s2;
        //cout << Cchar2int(ss2) << endl;
    
        char* c = int2char(1234);
        cout << *c << endl;
    
        return 0;
    }
  • 相关阅读:
    今日总结
    微任务与宏任务
    20171128微信小程序
    20171128-微信小程序之点餐
    git
    第二次学习Javascript笔记
    base64图片
    网页布局基础-css版
    StuQ技能图谱——前端
    前端开发工具
  • 原文地址:https://www.cnblogs.com/Chilly2015/p/5638250.html
Copyright © 2020-2023  润新知