简体   繁体   中英

Hope std::string::operator[] could return unsigned char

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM