【问题标题】:What is the proper way to convert an int to wchar_t?将 int 转换为 wchar_t 的正确方法是什么?
【发布时间】:2012-08-16 19:38:33
【问题描述】:

说你有“方法”

int Read(...)
{
    unsigned char Byte = 0;
    if(!ReadFile(.., &byte, 1,...))
        return -1;

    return Byte;
}


int ReadBlock(LPWSTR buffer, int cchBuffer ...)
{
    int c = 0;
    int cnt = 0;
    do
    {
        if( (c=Read(...)) != -1 )
            buffer[num++] = c; // Here.
    } while( num < ccBuffer );
    return cnt;
}

将 int 正确地转换为 WCHAR 的正确方法是什么?

【问题讨论】:

  • 你有什么问题?
  • (wchar_t)the_int 有什么问题?

标签: c++ windows type-conversion wchar


【解决方案1】:

阅读When should static_cast, dynamic_cast and reinterpret_cast be used? 后,我意识到是我对选角知识的缺乏促使我提出了这个问题。

【讨论】:

    【解决方案2】:

    使用mbstowcs(多字节字符串转宽字符串):

    int ReadBlock(LPWSTR buffer, int cchBuffer ...)
    {
        int c = 0;
        std::vector<char> narrow;
        while((c=Read(...)) != -1 )
           narrow.push_back(c);
        }
        narrow.push_back(0);
        mbstowcs(buffer, &narrow.front(), cchBuffer);
    }
    

    mbstowcs 使用当前语言环境,因此应该与您输入的编码相匹配。

    【讨论】:

    • @yanbellavance:听起来很奇怪。编写一个演示问题的小程序,然后您可以提出一个新问题。但是当您尝试隔离问题时,您可能会自己发现问题。
    【解决方案3】:
    convert char <= => wchar
    in windows:
    MultiByteToWideChar
    WideCharToMultiByte
    
    in linux:
    mbsrtowcs
    wcsrtombs
    

    【讨论】:

      【解决方案4】:
      #include<tchar.h>
      
      int main()
      {
          int integer = 0;
          wchar_t wideCharacter = (wchar_t)integer;
      
          return 0;
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-18
        • 1970-01-01
        • 1970-01-01
        • 2018-10-09
        • 1970-01-01
        • 1970-01-01
        • 2010-09-23
        • 2015-05-15
        相关资源
        最近更新 更多