【问题标题】:How to convert an int to ASCII char C++如何将 int 转换为 ASCII char C++
【发布时间】:2013-04-15 05:56:42
【问题描述】:

我必须将 int 转换为 ASCII 字符串。 基本上,我想要这个:

    int iTest = 128;
    char ca[3];
??? --> **SOLUTION :** sprintf(ca,"%d",iTest);

结果:

 ca[0] = 0x31;--> Hexcode of '1'
 ca[1] = 0x32;
 ca[2] = 0x38;

【问题讨论】:

    标签: c++ hex type-conversion ascii arrays


    【解决方案1】:

    使用std::string 和std::to_string:

    #include <string>
    #include <iostream>
    
    using namespace std;
    
    ...
    
    int iTest = 128;
    
    string ca = to_string(iTest);
    
    for (int i = 0; i < ca.size(); i++)
    {
        cout << hex << "0x" << (int) ca[i] << endl;
    }
    

    结果:

    0x31
    0x32
    0x38
    

    【讨论】:

    • sprintf(ca,"%d",iTest);也很好用,谢谢大家:D
    • 是的,但是使用 C++ 建议使用类型安全的方法。
    【解决方案2】:
    for each digit
        ca[ i ] = digit + '0';
    

    注意事项:

    • 注意数字的不同长度
    • 根据数字的“长度”(位数)动态分配ca
    • 可以通过使用 % 和 / 运算符来进行模数和除法运算来完成对每个数字的迭代。

    【讨论】:

      【解决方案3】:

      使用模和除法运算符得到每个数字,然后打印每个数字加上'0'。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-11
        • 1970-01-01
        • 2017-01-22
        • 1970-01-01
        相关资源
        最近更新 更多