gpt4 book ai didi

c++ - ASCII 到 dec 存储在字符串中

转载 作者:行者123 更新时间:2023-11-28 04:29:00 25 4
gpt4 key购买 nike

字符串 str_hex 包含字母 A-J 的十六进制值,对应于十进制值 65-74。我正在尝试将每个十六进制值转换为其十进制值 following this example .它适用于 for 循环内的 std::cout 情况,但输出-std::string 仍然具有 ascii 值。为什么这不起作用或者是否有更好/更合适的方法来构建我的输出字符串?

#include <string>
#include <iostream>
#include <stdint.h>

int main()
{

std::string str_hex("\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b", 10);
std::string str_output = "";

for (int i = 0; i < 10; ++i)
{
uint8_t tmp = str_hex[i];
str_output.append(1, (unsigned)tmp);
std::cout << "cout+for: " << (unsigned)tmp << std::endl;
if(i<9)
str_output.append(1, '-');
}
std::cout << std::endl << "cout+str_append: " << str_output << std::endl;

return 0;
}

编译并运行该程序会得到以下输出:

cout+for: 65
cout+for: 66
cout+for: 67
...

cout+str_append: A-B-C-D-E-F-G-H-I-J

期望的输出是:

cout+str_append: 65-66-67-68-...

最佳答案

string::append 方法在各种重载中接受一个 size_t 和一个 char,参见 reference .

string& append (size_t n, char c);

因此,在你的代码行中

str_output.append(1, (unsigned)tmp);

您正在隐式地将无符号 tmp 转换为 char,即转换为单个字母。要获得所需的输出,您必须将 tmp 转换为包含数字的字符串,然后将其附加到 str_output。您可以使用

str_output+=std::to_string(tmp);

代替 str_output.append(1, (unsigned)tmp);

关于c++ - ASCII 到 dec 存储在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53468289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com