which is the best way to convert a wstring to a string?

Pages: 12
Helios, I don't know the answer to your question?


What encoding are you going to assume those byte sequences are in? Latin1, UTF-8, or something else?


How (and where) do I define the encoding used?


suppose I have a stream (say an ifstream), how do I tell that ifstream which encoding to use?


You don't. My question was about your intentions. What encoding do you want your program to use? Do you care?
Earlier your said
I am just looking for how to transform a string into a wstring and a wstring into a string.
So what's the exact problem that you're trying to solve? If you just need to momentarily convert an std::string into an std::wstring such that you can later reverse the conversion, that's easy.
If you need to momentarily convert an std::wstring into an std::string such that you can later reverse the conversion, that's also doable, but it's a different problem with a different solution.
Thanks to all your help, I have solved the problem I had. The final version of the solution is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
namespace JD::StringLib
{
	//////////////////////////  wstring -> string
	std::string to_string(std::wstring wstr)
	{
		std::vector<char> buf(wstr.size());
		std::use_facet<std::ctype<wchar_t>>(std::locale{}).narrow(wstr.data(), wstr.data() + wstr.size(), '?', buf.data());

		return std::string(buf.data(), buf.size());
	}

	std::wstring to_wstring(std::string  str)
	{
		std::vector<wchar_t> buf(str.size());
		std::use_facet<std::ctype<wchar_t>>(std::locale{}).widen(str.data(), str.data() + str.size(), buf.data());

		return std::wstring(buf.data(), buf.size());
	}

	void testConversions()
	{
		for (int i=0; i < 256; ++i)
		{
			char c = static_cast<char>( i);
			std::string s{ c };
			auto res = to_wstring(s);

			char wc = static_cast<char>(res[0]);
			assert(c == wc);

			int j = 0;
		}
	}
}


Thanks...


Juan
Topic archived. No new replies allowed.
Pages: 12