C++中 int char 的相互轉換

特別注意char 只能處理單個字符如,1,2,3到9等,不能接收11,11等多位數字 

// 取到一個char的ASCII值

    char c='A';

    int i=c;

    printf("%d",i);

    //值爲數字的char轉爲對應數字

    char c1='3';

    int c1int=c1-'0';

    //int轉爲char型

    int i2=4;

    char c2=i2+'0';

    printf("%c",c2);

一個數(而不是一個數字) 如何轉爲char str[]呢?

代碼來自 http://bbs.csdn.net/topics/70251034

    char tmp[16];
    int isNegtive = 0;
    int index;

    if(m < 0)
    {
        isNegtive = 1;
        m = - m;
    }

    tmp[15] = '\0';
    index = 14;
    do 
    {
        tmp[index--] = m % 10 + '0'; //+'0' 不能少  否則存入的ASCII值
        m /= 10;
    } while (m > 0);

    if(isNegtive)
        tmp[index--] = '-';
    
    //這裏如果不願調用庫函數,可以使用for循環拷貝字符
    strcpy(buf, tmp + index + 1);

    return buf;

如果涉及到較複雜的轉換可以採用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    int n = 65535;
    char t[256];
    string s;
 
    sprintf(t, "%d", n);
    s = t;
    cout << s << endl;
 
    return 0;
}

或者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//第二種方法
#include <iostream>
#include <string>
#include <strstream>
using namespace std;
 
int main()
{
    int n = 65535;
    strstream ss;
    string s;
    ss << n;
    ss >> s;
    cout << s << endl;
 
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章