Goodmorning,
Can anyone tell me how to convert a TCHAR to a std::string ??
Thanks....
Brief follow-up to what and already covered: the easy case is the non-UNICODE build (TCHAR is a narrow char) — a direct assignment into a std::string is fine. The harder, real-world case is when TCHAR is wide (wchar_t): avoid wcstombs for anything beyond simple ASCII because it depends on the C locale and can silently mangle non‑English text. On Windows the reliable approach is an explicit UTF-16 -> UTF-8 conversion with WideCharToMultiByte so the resulting std::string is well-defined.
A compact, safe helper (Windows) looks like this:
#include <windows.h>
#include <string>
std::string TCHAR_to_string(const TCHAR* t)
{
#ifdef UNICODE
if (!t) return {};
int needed = WideCharToMultiByte(CP_UTF8, 0, t, -1, nullptr, 0, nullptr, nullptr);
if (needed == 0) return {}; // conversion error
std::string out(needed, '\0');
WideCharToMultiByte(CP_UTF8, 0, t, -1, &out[0], needed, nullptr, nullptr);
out.resize(needed - 1); // drop terminating null
return out;
#else
return std::string(t ? t : "");
#endif
} Alternatives: platform-independent libraries (Boost.Locale, ICU) handle character sets robustly; the C++ <codecvt>/wstring_convert helpers exist but are deprecated in newer standards and not recommended for new code. Practical tips: decide on a canonical internal encoding (UTF-8 is a good default), prefer explicit std::string/std::wstring over TCHAR in new code, always specify CP_UTF8 when converting on Windows, check for errors from the conversion API, and watch null-termination/size off-by-one issues.
Jump to Post— Ancient Dragon 5,243TCHAR is just a macro that is defined to be either char* or wchar_t*, depending on whether your program is compiled with UNICODE or not. If not UNICODE then use just simple assignment to convert to std::string. If the program is UNICODE then use one of the conversion functions, such …
TCHAR is just a macro that is defined to be either char* or wchar_t*, depending on whether your program is compiled with UNICODE or not. If not UNICODE then use just simple assignment to convert to std::string. If the program is UNICODE then use one of the conversion functions, such as wcstombs(). That function works ok with English language, but I don't know about other languages.
Thanks Ancient Dragon, 'problem' solved....
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.