【问题标题】:decimal ascii value for unsigned char array无符号字符数组的十进制 ascii 值
【发布时间】:2017-01-18 19:33:29
【问题描述】:

如何将 char 数组转换为其等效的 ascii 十进制数组?我尝试在 QT 中使用 QString 和 QbyteArray。但它不起作用。

i/p: "1,9,10,2"

o/p: "4944574449484450" (1 的 ascii 十进制值为 49, , ascii 十进制值为 44, 9 的 ascii 十进制值为 57,依此类推..)。

【问题讨论】:

  • 已经是了。打印时遇到问题吗?
  • 是的,在调试器中显示值。但是我打印出来了,它显示出不同的东西。

标签: c++ c arrays qt


【解决方案1】:

如何将 char 数组转换为等效的 ascii 十进制数组?

您没有,它已经以这种方式存储。如果您想将数组打印为 ASCII 的十进制数字,只需相应地输出(作为整数):

char str[] = "1,9,10,2";
for( const char *s = str; *s; ++s ) std::cout << static_cast<int>( *s ) << ","; 
// just output number instead of character

C++ 中char 是类似于int 的数值类型,区别在于std::ostream 输出char 作为符号而int 和其他整数类型作为整数。

【讨论】:

    【解决方案2】:

    您可以轻松地做到这一点。它是 C++,但它可以在 C 中使用适当的 include 和 printf 代替 std:cout。

    int main() {
        char input[] = "1,9,10,2";
        char output[3*sizeof(input) + 1];
    
        output[0] = '\0';
        for (size_t i = 0; i < strlen(input); i++) {
            sprintf(output, "%s%d", output, input[i]);
        }
    
        std::cout << input << std::endl;
        std::cout << output << std::endl;
    
        return 0;
    }
    

    听从@Nathan 的一些提示,现在应该会更好...

    【讨论】:

    • @latedeveloper 很抱歉您无法运行它。为什么不应该呢?
    • char output[2*strlen(input) + 1]; 是 VLA,不是标准 C++。
    • @Nitro 内森说了什么。
    • @NathanOliver 对……我猜你可以用“sizeof”代替“strlen”……
    • 仍然是一个非常脆弱的解决方案。您基本上使用的假设是字符映射到 [10, 99] 范围内的值。如果情况并非如此,那么问题就会接踵而至。
    【解决方案3】:

    这应该可以工作

    char arr[] = {'1','9','2'};
    std::vector<int> vec(size); //size of the char array - in this case 3
    for(int i = 0; i < size; i++)
    {
       vec[i] = arr[i];
    }
    

    【讨论】:

    • 为什么不加std:size_t size = sizeof(arr) / sizeof(char);
    • 分配给int时不需要强制转换char
    • 关于int* ptr = new int[size],我可以推销std::vector&lt;int&gt; vec(size);吗?
    猜你喜欢
    • 2014-10-17
    • 2022-01-09
    • 2022-01-09
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    相关资源
    最近更新 更多