[英]basic_string of unsigned char Value Type
So, string comes with the value type of char
. 因此,string带有char
的值类型。 I want a string of value type unsigned char
. 我想要一个值类型为unsigned char
的字符串。 Why i want such a thing is because i am currently writing a program which converts large input of hexadecimal to decimal, and i am using strings to calculate the result. 为什么我想要这样的事情是因为我当前正在编写一个程序,将十六进制的大量输入转换为十进制,并且我正在使用字符串来计算结果。 But the range of char, which is -128 to 127 is too small, unsigned char with range 0 to 255 would work perfectly instead. 但是char的范围(从-128到127)太小,取而代之的是0到255范围内的无符号char。 Consider this code: 考虑以下代码:
#include<iostream>
using namespace std;
int main()
{
typedef basic_string<unsigned char> u_string;
u_string x= "Hello!";
return 0;
}
But when i try to compile, it shows 2 errors, one is _invalid conversion from const char* to unsigned const char*_ and the other is initializing argument 1 of std::basic_string<_CharT, _Traits, _Alloc>::basic_string... (it goes on) 但是当我尝试编译时,它显示2个错误,一个是_从const char *到无符号const char * _的无效转换,另一个是初始化std :: basic_string <_CharT,_Traits,_Alloc> :: basic_string的参数1。 (如此下去)
EDIT: "Why does the problem "converts large input of hexadecimal to decimal" require initializing a u_string with a string literal?" 编辑:“为什么问题”将十六进制的大输入转换为十进制“需要初始化带有字符串文字的u_string?” While calculating, each time i shift to the left of the hexadecimal number, i multiply by 16. At most the result is going to be 16x9=144, which surpasses the limit of 127, and it makes it negative value. 在计算时,每当我向十六进制数的左边移动时,我便乘以16。最多结果将是16x9 = 144,超过了127的极限,并使其为负值。 Also, i have to initialize it like this: 另外,我必须像这样初始化它:
x="0"; X = “0”; x[0] -='0'; x [0]-='0';
Because i want it to be 0 in value. 因为我希望它的价值是0。 if the variable is null, then i can't perform operations on it, if it is 0, then i can. 如果变量为null,则无法对其执行操作;如果为0,则可以。
So, what should i do? 所以我该怎么做?
String literals are const char
and you are assigning them to a const unsigned char
. 字符串文字是const char
,您正在将它们分配给const unsigned char
。
Two solution you have: 您有两种解决方案:
First, Copy string from standard strings to your element by element. 首先,将字符串从标准字符串复制到元素中。
Second, Write your own user-literal for your string class: 其次,为您的字符串类编写自己的用户文字 :
inline constexpr const unsigned char * operator"" _us(const char *s,unsigned int)
{
return (const unsigned char *) s;
}
// OR
u_string operator"" _us(const char *s, unsigned int len)
{
return u_string(s, s+len);
}
u_string x = "Hello!"_us;
An alternative solution would be to make your compiler treat char
as unsigned. 一种替代解决方案是使您的编译器将char
视为无符号。 There are compiler flags for this: 为此有一些编译器标志:
/J
MSVC: /J
-funsigned-char
GCC,C语,ICC: -funsigned-char
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.