将std::string强制使用无符号字符(0至255)而非有符号字符(-128至127)?

3

有没有办法强制字符串使用unsigned char而不是char?也许在构造函数中?

我需要进行算术运算(主要是递增,递减, ~(按位非)),并且我需要能够使用溢出255 ++ == 0 ... 而不是 127++ == -128(和下溢0-- == 255...)

我不确定问题是否有意义,在这里列出一个很好的关于该主题(流)的问题以便有更好的理解:Why do C++ streams use char instead of unsigned char?

我不是在尝试将字符串转换为unsigned char,我找到了很多关于如何在两者之间转换的问题。


1
与答案无关:char 不一定是(-128到127)。它可能会作为 signed charunsigned char 表现。 - Mohit Jain
你实际上是将字符串作为字符串使用吗? - MikeMB
我将其作为字符串使用;从getopt中复制(strdup())到字符串变量optarg,我使用类似以下的代码来去除空格while(fin >> skipws >> ch) my_string.append(&ch); (ch是char类型),我计划使用类似my_string[i]++的代码来进行递增... - Kyslik
我询问是为了决定是否应该点赞std::vectorstd::basic_string的答案。std::basic_string<unsigned char>似乎更接近你的问题,但是my_string[i]++表明你并没有真正将内容视为字符串,而是字节的集合,在这种情况下,我会更喜欢std::vector<unsigned char>,但这也需要你改变代码的其他部分。 - MikeMB
哦,我一点也不是C++大师,我肯定要改很多代码。首先,我使用的是纯char/unsigned char(而非string),然后我重写了它以使用字符串,因为有很多方法。现在,我正在决定仅在需要使用溢出和下溢(以及~)的代码部分中使用ustring。谢谢你的意见。 - Kyslik
3个回答

5

您可以使用:

typedef std::basic_string<unsigned char> ustring;

然后使用ustring代替std::string


谢谢,我会试一下 :) - Kyslik
这是可能的吗?ustring test; test = "ABCD"; - Kyslik
1
不行,你不能这样做,因为 ustring 没有一个 operator=(const char*) - Patryk
@Patryk 我明白了,我正在使用你提供的函数之一将字符串转换为ustring。谢谢你。(你也让我明白了字符串的真正含义)+1。 - Kyslik
@Kyslik 一种方法是 ustring test = reinterpret_cast<const unsigned char *>("abcd"); ,但我不建议这样做。另一种方法是您提到的转换器函数。 - Mohit Jain

4

std::string实际上只是一个std::basic_string<char>

你需要的是一个std::basic_string<unsigned char>

这个答案这个SO线程中有一些不错的转换方法。

#include <string>
#include <iostream>

typedef std::basic_string<unsigned char> ustring;

inline ustring convert(const std::string& sys_enc) {
  return ustring( sys_enc.begin(), sys_enc.end() );
}

template< std::size_t N >
inline ustring convert(const char (&array)[N]) {
  return ustring( array, array+N );
}

inline ustring convert(const char* pstr) {
  return ustring( reinterpret_cast<const ustring::value_type*>(pstr) );
}

std::ostream& operator<<(std::ostream& os, const ustring& u)
{
    for(auto c : u)
      os << c;
    return os;
}

int main()
{
    ustring u1 = convert(std::string("hello"));
    std::cout << u1 << '\n';

    // -----------------------
    char chars[] = { 67, 43, 43 };
    ustring u2 = convert(chars);
    std::cout << u2 << '\n';

    // -----------------------
    ustring u3 = convert("hello");
    std::cout << u3 << '\n';
}

coliru

->

{{链接1:coliru}}


1
简单地使用一个:

std::vector<unsigned char> v;

我的变量声明是字符串 my_string; - Kyslik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接