Sunday, December 25, 2011

How to convert LPWSTR to string in VC++

Author: ArkM
Source: http://www.daniweb.com/software-development/cpp/threads/155420



C++ Syntax (Toggle Plain Text)
  1. bool cvtLPW2stdstring(std::string& s, const LPWSTR pw,
  2. UINT codepage = CP_ACP)
  3. {
  4. bool res = false;
  5. char* p = 0;
  6. int bsz;
  7.  
  8. bsz = WideCharToMultiByte(codepage,
  9. 0,
  10. pw,-1,
  11. 0,0,
  12. 0,0);
  13. if (bsz > 0) {
  14. p = new char[bsz];
  15. int rc = WideCharToMultiByte(codepage,
  16. 0,
  17. pw,-1,
  18. p,bsz,
  19. 0,0);
  20. if (rc != 0) {
  21. p[bsz-1] = 0;
  22. s = p;
  23. res = true;
  24. }
  25. }
  26. delete [] p;
  27. return res;
  28. }
  29.  
  30. int main()
  31. {
  32. wchar_t msg[] = L"Hello, world!";
  33. std::string s("\?");
  34.  
  35. cvtLPW2stdstring(s,msg);
  36. std::cout << s << std::endl;
  37.  
  38. return 0;
  39. }


No comments: