【问题标题】:How to convert a char * starting with "\0" to unsigned int? [closed]如何将以“\ 0”开头的char *转换为无符号整数? [关闭]
【发布时间】:2019-08-10 20:18:16
【问题描述】:

我有一个问题,我需要将字符串“\005”转换为无符号整数值 5。最好的方法是什么?

这是从 curl 响应中获取响应值。

int main()
{

    char *ptr = "\005";
    stringstream strValue;
    strValue << *ptr;

    unsigned int intValue;
    strValue >> intValue;

    cout << ptr << endl;
    cout << intValue << endl;

    return 0;
}

期望输出为 5 但得到

0

【问题讨论】:

  • 这不是很明显吗? unsigned int n=*ptr;?
  • 您是否有字符串\005(即首先带有实际反斜杠)或[NUL]05(即第一个字符是ASCII 0)字节?
  • int intvalue = 5; 会做到的。要获得更有用的答案,您需要解释该字符串中每个字符的含义,即值是如何编码的?值 6 将如何编码? 10? 33?
  • "这是从 curl 响应中获取响应值。" - 我知道“\005”是来自http响应的字符串。所以需要解析才能得到 5
  • 您正在尝试将编码为数字 5 的(不可打印的)字符解释为数字。 (行为就像你写了char ptr[] = {5, 0};。)

标签: c++ string int


【解决方案1】:

如何将“\0”开头的char *转换为unsigned int?

"\005"

字符串"\005" 不以字符'\0' 开头。它以字符 '\005' 开头,这是一个八进制转义序列,表示八进制数 005,十进制表示为 5。您可以像这样将字符转换为unsigned int 类型:

unsigned int n = ptr[0];

附: char *ptr = "\005" 自 C++11 以来格式错误,因为字符串文字不能隐式转换为指向 char 的非常量指针。

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多