该字符串str_hex
包含字母 AJ 的十六进制值,对应于十进制值 65-74。我正在尝试按照此示例将每个十六进制值转换为其十进制值。它适用于std::cout
for 循环内的情况,但输出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
在各种重载中接受 asize_t
和 a char
,请参阅参考资料。
string& append (size_t n, char c);
因此,在您的代码行中
str_output.append(1, (unsigned)tmp);
您隐式地将无符号tmp
转换为字符,即转换为单个字母。要获得您想要的输出,您必须转换tmp
为包含数字的字符串,然后将其附加到str_output
. 你可以通过使用做到这一点
str_output+=std::to_string(tmp);
而不是str_output.append(1, (unsigned)tmp);
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句