【发布时间】:2015-07-30 00:58:00
【问题描述】:
如果 s 在 C++ 中是 string 类型,s[n] 将返回 char,而不是 unsigned char。这给我带来了很多问题,因为我必须到处进行类型转换。
以下代码不会打印“是”。
#include <string>
#include <iostream>
using namespace std;
typedef unsigned long ulong;
typedef unsigned int uint;
typedef unsigned short uint16;
typedef unsigned char uchar;
int main(int argc, char *argv[]) {
string s = "h\x8fllo world";
printf("%d\n", s[1]);
if (s[1] == 0x8f) {
printf("yes\n");
}
return 0;
}
我可以通过将上面的内容更改为if ((uchar*)(s[1] == 0x8f) { 来使其工作,但是出现的次数太多了。我真的希望string 类上的[] 运算符可以返回unsigned char!!有没有办法做到这一点?
【问题讨论】:
-
(1) 查看具有
std::uint16_t和类似内容的 cstdint 标头。 (2) 使用std::vector<unsigned char>? -
“这给我带来了很多问题,因为我必须到处进行类型转换。” 当您决定使用
unsigned char时,您没有为自己制造问题吗? “到处”?你这样做的原因是什么? -
if ((uchar*)(s[1] == 0x8f)不是你要写的,是吗? -
更多关于
char签名:stackoverflow.com/questions/17097537/…