Naohiro19

WStrToStr と StrToWStr 関数を実装するコード(ChatGPTからのコピペ)

Aug 30th, 2024 (edited)
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <windows.h>
  2. #include <string>
  3. #include <vector>
  4. #include <stdexcept>
  5.  
  6. // WStrToStr: std::wstring から std::string への変換
  7. std::string WStrToStr(const std::wstring& wstr) {
  8.     // 最初に変換先のサイズを取得
  9.     int size_needed = WideCharToMultiByte(932, 0, wstr.c_str(), static_cast<int>(wstr.size()), NULL, 0, NULL, NULL);
  10.     if (size_needed <= 0) {
  11.         throw std::runtime_error("WideCharToMultiByte failed to get the size needed.");
  12.     }
  13.  
  14.     // バッファを確保
  15.     std::vector<char> buffer(size_needed);
  16.  
  17.     // 実際の変換
  18.     int result = WideCharToMultiByte(932, 0, wstr.c_str(), static_cast<int>(wstr.size()), buffer.data(), size_needed, NULL, NULL);
  19.     if (result <= 0) {
  20.         throw std::runtime_error("WideCharToMultiByte failed during conversion.");
  21.     }
  22.  
  23.     return std::string(buffer.data(), buffer.size());
  24. }
  25.  
  26. // StrToWStr: std::string から std::wstring への変換
  27. std::wstring StrToWStr(const std::string& str) {
  28.     // 最初に変換先のサイズを取得
  29.     int size_needed = MultiByteToWideChar(932, 0, str.c_str(), static_cast<int>(str.size()), NULL, 0);
  30.     if (size_needed <= 0) {
  31.         throw std::runtime_error("MultiByteToWideChar failed to get the size needed.");
  32.     }
  33.  
  34.     // バッファを確保
  35.     std::vector<wchar_t> buffer(size_needed);
  36.  
  37.     // 実際の変換
  38.     int result = MultiByteToWideChar(932, 0, str.c_str(), static_cast<int>(str.size()), buffer.data(), size_needed);
  39.     if (result <= 0) {
  40.         throw std::runtime_error("MultiByteToWideChar failed during conversion.");
  41.     }
  42.  
  43.     return std::wstring(buffer.data(), buffer.size());
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment