[英]Hope std::string::operator[] could return unsigned char
如果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
!!有辦法嗎?
不, std::string
是std::basic_string<char, ...>
,並且您無能為力或者應該做任何改變。
您可以強制將實現的char
設置為無符號( 某些編譯器允許使用此符號),並將斷言粘貼在各處,以防止代碼使用帶符號的char
類型進行編譯。
您可以切換到std::basic_string<unsigned char, ...>
甚至std::vector<unsigned char>
。
但是,就我個人而言,我只是將該字符與另一個字符(而不是整數)進行比較:
if (s[1] == '\x8f')
我認為這還是更好的代碼。
您應該能夠使用std::basic_string<unsigned char>
( std::string
實際上只是std::basic_string<char>
的typedef
)。 這將意味着修改您的代碼以使用新的typedef
而不是std::string
,盡管那應該是一個相當簡單的搜索和替換重構。
有關更多詳細信息,請參見未簽名字符的字符串 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.