访问 std::string 数组的元素

Accessing elements of the std::string array

如何在 C++ 中访问以下数组元素并以十六进制格式打印 uint8_t 类型的元素?

std::string arr[] = {"0x01","0x02","0x03","0x04","0x05","0x06"}

如何使用 c_str() 打印每个元素?

正如 Dmitri 评论的那样,您的数组元素的类型为 std::string。它们确实对格式化为十六进制的无符号整数进行编码。如果您的目标是简单地打印它们,这就足够了:

#include <iostream>

int main() {
    std::string arr[] = {"0x01","0x02","0x03","0x04","0x05","0x06"};
    for (int i = 0; i < 6; i++) {
        std::cout << arr[i] << std::endl;
    }
}

如果您需要数组中的值是uint8_t类型,您需要先显式转换它们。

uint8_t 是一种特殊的 int 类型。标准允许格式化方法将其处理为与unsigned char相同。

如果您真的想将每个字符串转换为 uint8_t,则必须使用 int 作为输入和输出的中间值:

std::string arr[] = { "0x01","0x02","0x03","0x04","0x05","0x06" };

for (const std::string& s : arr) {
    std::stringstream str(s);          // use a stringstream for the conversion
    int i;
    str >> std::hex >> i;
    uint8_t u = i;                     // you have the expected uint8_t
    // but you will have to cast them to int again to print them
    std::cout << static_cast<int>(u) << ' ';
}

要以十六进制打印 int,您必须 #include <iomanip> 并使用 std::hex:

    std::cout << std::hex << static_cast<int>(u) << ' ';

如果您的目标是解析字符串,请按以下步骤操作:

#include <cstdint>
#include <cstdio>
#include <string>

int main() {
  std::string arr[] = {"0x01", "0x02", "0x03", "0x04", "0x05", "0x06"};

  std::uint8_t arr2[6];

  for (std::size_t i = 0; i < 6; ++i) arr2[i] = std::stoi(arr[i], nullptr, 16);

  for (auto e : arr2) std::printf("%#x\n", e);
}