【问题标题】:sscanf into uint8 array failssscanf 进入 uint8 数组失败
【发布时间】:2019-12-17 17:54:08
【问题描述】:

我正在使用 sscanf 将 MAC 地址从字符串放入 uint8 数组。由于某种原因,uint8 数组全部为空。

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    std::string mac = "00:00:00:00:00:00";
    uint8_t smac[7];
    memset(smac, 0, 7);
    sscanf(
        mac.c_str(), 
        "%hhu:%hhu:%hhu:%hhu:%hhu:%hhu",
        &smac[0],
        &smac[1],
        &smac[2],
        &smac[3],
        &smac[4],
        &smac[5]
    );

    std::cout << "string: " << mac << std::endl;
    std::cout << "uint8_t: "<< smac;

    return 0;
}

【问题讨论】:

  • 这能回答你的问题吗? uint8_t can't be printed with cout
  • @UnholySheep 这是打印uint8_ts 的数组。这是相似的,但不是同一个问题。
  • 我认为sscanf 格式字符串在嘲笑我们。它有充分的理由。结果代码被忽略了。
  • @RobertS-ReinstateMonica iostream 可能有 #include &lt;cstdio&gt;using namespace std;std::sscanf 拉入全局命名空间。
  • @JL2210 那只是我说返回码没有用太多字检查。 “hhu hhu hhu hhu hhu hhu”格式字符串让我想起了笑起来的赫特人贾巴。

标签: c++


【解决方案1】:

uint8_t 在大多数平台上是typedef 对应unsigned char。因此,cout 尝试将其打印为字符串,但遇到第一个字符为空字节(或字符串终止符),因此停止打印。

这里的解决方案是单独打印所有 MAC 地址成员:

for(int c = 0; c < sizeof(smac); c++)
{
    std::cout << +smac[c];
    if(c != sizeof(smac) - 1)
        std::cout << "::";
}
std::cout << '\n';

这里的+ 执行整数提升,因此smac[c] 将打印为数字而不是字符。

【讨论】:

  • 谢谢 - 我真正的问题是我仍然得到所有0s。如果我的 mac 是“FF:FF...”,它仍然是全 0。
  • @errno_44 好吧,您输入的是零并期待...不是零?我的意思是,"00:00:00:00:00:00" 在我看来全为零。
【解决方案2】:

uint8_tunsigned char 类型通常等效于编译器。输出char(无符号或无符号)数组的惯例是在达到零值时停止,因为这表示字符串的结尾。

【讨论】:

    猜你喜欢
    • 2012-04-29
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    相关资源
    最近更新 更多