i am trying to concatenate an unsigned char to a string but its not workingCode:int main(){
string s= "ABCDE";
unsigned char a='vv;
s=s+a;
}
Printable View
i am trying to concatenate an unsigned char to a string but its not workingCode:int main(){
string s= "ABCDE";
unsigned char a='vv;
s=s+a;
}
Code:#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
std::string stringDemo = "Hello";
char c = 'v';
stringDemo += c;
std::cout << stringDemo; // prints Hellov
stringDemo.push_back(c);
std::cout << stringDemo; // prints Hellovv
}
Why do you want to use an unsigned char?
Anyway, if you know that the value of the unsigned char will be in the range of char, the solution is to cast:
Code:stringDemo.push_back(static_cast<char>(c));
Ah, then instead of using a std::string, use a std::vector<unsigned char>.
Or use wstring.
Although frankly, wstring is always such a pain in the .... to work with.Code:#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
std::wstring stringDemo = L"Hello";
unsigned char c = 'v';
stringDemo += c;
std::wcout << stringDemo; // prints Hellov
}
Using wstring will allow you to do this though:
Code:std::wstring stringDemo = L"Hello";
unsigned char c = static_cast<unsigned char>(199);
stringDemo += c;
std::wcout << stringDemo; // prints Hello╟
I may be wrong, but in theory, the range of a wchar_t may well be the same as that of a signed char, since they have the same constraints on implementation defined limits. So, I reason if that if you want to store unsigned chars, then store unsigned chars.Quote:
Originally Posted by Serapth
Can't basic_string<unsigned char> be used ?
I'm not sure that basic_string is portable or standard-compliant. to my knowledge, string and wstring are specified by the standard, but no mention of how they must be implemented. I may be wrong about this.
basic_string is part of the standard library, but then the stuff like string literals won't exist for basic_string<unsigned char> (except maybe now there's some user defined literals thing, but I'm not familiar with that at all).Quote:
Originally Posted by Elkvis
basic_string is standard, but char_traits is not standard for unsigned char. Thus, you probably won't be able to use basic_string with unsigned char.
You can supply your own traits struct/class if you want, though.
This works, but I couldn't get it working with any sort of streams.
How would I use custom traits ?
Code:basic_string<unsigned char> s;
s+=static_cast<unsigned char>(200);
Aren't user defined literals about adding custom suffixes to data ?