cfischer
cfischer

Reputation: 24912

How to create a std::wstring using the ascii codes of characters in C++?

I need to create a wstring with the chars that have the following ascii values: 30, 29, 28, 27, 26, 25.

In VB6, I would do asc(30) + asc(29)+ etc...

What's the C++ equivalent?

Thanks!

Upvotes: 1

Views: 2271

Answers (2)

user52875
user52875

Reputation: 3058

Is this a trick question about character set conversion? :) Because the standard does not guarantee that an ASCII character is represented by its ASCII integer value in a wchar_t (even though for most compilers/systems, this will be true). If it matters, explicitly widen your char using an appropriate locale:

std::wstring s;
std::locale loc("C"); // pick a locale with ASCII encoding

s.push_back(std::use_facet<std::ctype<wchar_t> >(loc).widen(30));
s.push_back(std::use_facet<std::ctype<wchar_t> >(loc).widen(29));
s.push_back(std::use_facet<std::ctype<wchar_t> >(loc).widen(28));

Don't terminate with a trailing 0, it is added when you convert the wstring to a wchar_t * by invoking .c_str()

Upvotes: 5

Patrick
Patrick

Reputation: 23629

An std::wstring is nothing more than an std::vector disguised as a string.

Therefore you should be able to use the push_back method, like this:

std::wstring s;

s.push_back(65);
s.push_back(0);

std::wcout << s << std::endl;

Don't forget the 0-terminator !

Upvotes: 1

Related Questions