1

if s is of type string in C++, s[n] will return a char, not unsigned char. This creates lots of problem for me since I have to do type conversion everywhere.

The following code will not print "yes".

#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;
}

I can make it work by changing the above to be if ((uchar*)(s[1] == 0x8f) {, but there are too many occurrences. I really hoped that the [] operator on string class could return a unsigned char!! Is there a way to do this?

packetie
  • 4,839
  • 8
  • 37
  • 72

2 Answers2

4

You should be able to use a std::basic_string<unsigned char> (std::string is really just a typedef to std::basic_string<char>). That will mean modifying your code to use your new typedef instead of std::string, though that should be a fairly simple search-and-replace refactoring.

See Strings of unsigned chars for more details.

Community
  • 1
  • 1
Trebor Rude
  • 1,904
  • 1
  • 21
  • 31
3

No, std::string is std::basic_string<char, ...>, and there's nothing you can or should do to change that.

You could force your implementation's char to be unsigned (some compilers allow this) and stick assertions everywhere to prevent your code from compiling with a signed char type.

You could switch to std::basic_string<unsigned char, ...> or even std::vector<unsigned char>.

But, personally, I'd just compare the character against another character (instead of an integer):

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

(live demo)

I think this is better code anyway.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055