【问题标题】:Hope std::string::operator[] could return unsigned char希望 std::string::operator[] 可以返回 unsigned char
【发布时间】: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&lt;unsigned char&gt; ?
  • “这给我带来了很多问题,因为我必须到处进行类型转换。” 当您决定使用 unsigned char 时,您没有为自己制造问题吗? “到处”?你这样做的原因是什么?
  • if ((uchar*)(s[1] == 0x8f) 不是你要写的,是吗?
  • 更多关于char签名:stackoverflow.com/questions/17097537/…

标签: c++ string


【解决方案1】:

您应该可以使用std::basic_string&lt;unsigned char&gt;std::string 实际上只是typedefstd::basic_string&lt;char&gt;)。这意味着修改您的代码以使用新的typedef 而不是std::string,尽管这应该是一个相当简单的搜索和替换重构。

更多详情请见Strings of unsigned chars

【讨论】:

  • 谢谢@Trebor_Rude。也喜欢你的回答。
【解决方案2】:

不,std::stringstd::basic_string&lt;char, ...&gt;,您无法或不应该做任何改变。

您可以强制实现的 char 未签名 (some compilers allow this) 并在各处粘贴断言,以防止您的代码使用已签名的 char 类型编译。

您可以切换到std::basic_string&lt;unsigned char, ...&gt; 甚至std::vector&lt;unsigned char&gt;

但是,就个人而言,我只是将字符与另一个字符(而不是整数)进行比较:

if (s[1] == '\x8f')

(live demo)

无论如何,我认为这是更好的代码。

【讨论】:

  • char 常量相比,而不是int 常量似乎显然是正确的做法。
  • 感谢@lightness-races-in-orbit。早该想到的。使用'\x8f' 的技巧很好!
  • @codingFun:我不会称其为“技巧”;这是默认的,首先要做的事情! :) (正如赫尔基尔所说)
  • @codingFun:如果你想让人们正确理解你,我建议你放弃这个习惯。 :)
  • 会的。谢谢@lightness-races-in-orbit。
猜你喜欢
  • 2010-10-22
  • 1970-01-01
  • 2013-07-18
  • 2011-07-23
  • 2021-02-24
  • 1970-01-01
  • 2012-05-13
  • 2018-12-02
  • 2012-03-07
相关资源
最近更新 更多