【问题标题】:Accessing elements of the std::string array访问 std::string 数组的元素
【发布时间】:2021-05-29 18:03:05
【问题描述】:

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

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

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

【问题讨论】:

  • 您可以使用下标运算符访问它们,例如arr[1] 用于第二个。但是它们都不是uint8_t类型,它们都是std::string
  • 是否可以使用 static_cast 或 reinterpret_cast?
  • “指向每个元素”是什么意思?你是说打印吗?
  • @MysteriousUser 是的
  • 实在不清楚你想做什么。你想打印数组中的字符串吗?还是其中一个字符串中字符的数值?为什么你特别需要c_str()

标签: c++ arrays string c-strings


【解决方案1】:

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 &lt;iomanip&gt; 并使用 std::hex

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

【讨论】:

  • 这给了我一个类似这样的错误:变量'std::stringstream str'有初始化程序但类型不完整
  • @VasudaR 你必须#include &lt;sstream&gt;
  • 不能打印为十六进制值吗?
【解决方案2】:

如果你的目标是解析字符串,你可以这样做:

#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);
}

【讨论】:

    【解决方案3】:

    正如 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 类型,则需要先显式转换它们。

    【讨论】:

    • 是的,我想打印 uint_8 类型的相同数组元素。
    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2020-07-09
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多