整數,字符,字符串間的轉換

#include <iostream>
#include <string>
#include <sstream>
#include <cmath>

using namespace std;

int main()
{
    int i;
    int num1=123456;
    int num2=1;
    string str="123456";
    char c_num='1';

    //單個數字轉字符
    char temp1;
    temp1 = num2 - 0 + '0';
    cout<<temp1<<endl;

    //數字轉字符串
    string temp2;
    stringstream ss;
    ss<<num1;
    ss>>temp2;
    cout<<temp2<<endl;

    //字符轉數字
    int temp3;
    temp3 = c_num - '0';
    cout<<temp3<<endl;

    //字符串轉數字
    int temp4=0;
    for(i=0;i<str.size();i++)
        temp4 += (str[i]-'0') * pow(10,str.size()-i-1);
    cout<<temp4<<endl;

    //字符轉字符串
    string temp5="";
    for(i=0;i<5;i++)
        temp5 += c_num;
    cout<<temp5<<endl;

    return 0;
}

1.單個數字 -> 字符

    用該數字減去0,再加上字符'0'即可

2.長數字 -> 字符串

    利用stringstream,該方法是通用方法,基本上任何類型都可以這麼轉換.

3.字符 -> 單個數字

    該字符減去字符'0'

4.字符串 -> 數字

    可以用stringstream,也可以從首位字符開始,減去'0'再乘以相應指數位。

5.字符 -> 字符串

    str += char 即可將字符加到字符串後

發佈了112 篇原創文章 · 獲贊 7 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章