【问题标题】:Force std::string to use unsigned char (0 to 255) instead of char (-128 to 127)强制 std::string 使用 unsigned char(0 到 255)而不是 char(-128 到 127)
【发布时间】:2016-06-03 19:31:36
【问题描述】:

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

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

我不确定这个问题是否有意义,在这里稍微说明一下这是一个关于主题(流)Why do C++ streams use char instead of unsigned char?987654321@

的好问题

我没有尝试将字符串转换为 unsigned char 我发现了很多关于如何在两者之间转换的问题。

【问题讨论】:

  • 与答案无关:char 不一定(-128 到 127)。它可能表现为signed charunsigned char
  • 你真的把字符串当成字符串用了吗?
  • 某种意义上我把它当作字符串使用;我将 (strdup()) 从 getopt 复制到字符串变量 optarg,我使用类似这样的东西来消除空格 while(fin >> skipws >> ch) my_string.append(&ch); ( ch 是 char 的类型),我计划使用类似 my_string[i]++ 的东西来增加......
  • 我询问是为了决定是否应该投票给std::vectorstd::basic_string 答案。 std::basic_string<unsigned char> 似乎更接近您的问题,但 my_string[i]++ 表示,您并没有真正将内容视为字符串,而是字节的集合,在这种情况下,我倾向于 std::vector<unsigned char> 但这需要您更改代码的其他部分。
  • 哦,我根本不是 c++ 大师,我肯定要更改很多代码。首先,我使用的是纯字符/无符号字符(不是字符串),然后我重写了它以使用字符串,因为有很多 .methods。现在我决定只在需要使用溢出和下溢(和〜)的代码的少数部分使用ustring。感谢您的意见。

标签: c++ string


【解决方案1】:

你可以使用:

typedef std::basic_string<unsigned char> ustring;

然后用ustring代替std::string

【讨论】:

  • 谢谢你,我会测试一下:)
  • 是否可以进行ustring测试;测试=“ABCD”; ?
  • 不,您不能这样做,因为您没有 operator=(const char*) 用于 ustring
  • @Patryk 我想,我正在使用您提供的函数之一将字符串转换为 ustring。谢谢你。 (你也明白字符串到底是什么)+1。
  • @Kyslik 一种方法是ustring test = reinterpret_cast&lt;const unsigned char *&gt;("abcd");,尽管我不会推荐它。另一个是您提到的转换器功能。
【解决方案2】:

std::string实际上只是一个std::basic_string&lt;char&gt;

你需要的是std::basic_string&lt;unsigned char&gt;

this answerfrom this SO thread中有一些不错的转换方法

#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

【讨论】:

    【解决方案3】:

    只需使用:

    std::vector<unsigned char> v;
    

    【讨论】:

    • 我的变量声明是string my_string;
    猜你喜欢
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 2011-11-13
    • 2014-12-11
    相关资源
    最近更新 更多