【问题标题】:How to copy/convert a char string to a wchar_t string in C?如何在 C 中将 char 字符串复制/转换为 wchar_t 字符串?
【发布时间】:2015-07-04 00:25:38
【问题描述】:

我环顾四周,从<wchar.h> 库中找到了一个使用swprintf 的程序。但是我尝试了这种方法,它没有工作。它只是说我运行程序时 program.exe 已停止工作。我将找到的示例程序复制到我自己的编译器中——这也不起作用。我将复制下面的程序:

#include <stdio.h>
#include <wchar.h>

int main(void)
{

 wchar_t NameBuffer[100];
 char *str1 ="c:\\Program Files\\test.txt";

   swprintf(NameBuffer,100,L"%s",str1);
   printf("%s\n",NameBuffer);

  return 0;
}

这段代码有问题还是我的编译器有问题?

【问题讨论】:

    标签: c string char wchar-t


    【解决方案1】:

    在上面的代码中,在 printf 行中

    printf("%s\n",NameBuffer);
    

    NameBuffer 不是 char * 类型的(转换后的)值,因此您通过不匹配 %s 及其对应参数来调用未定义行为。

    试试

    wprintf(L"%ls\n", NameBuffer);
    

    或

    printf("%ls\n", NameBuffer);
    

    您可能还想将str1 定义为指向 const 的指针

    const char *str1 = "c:\\Program Files\\test.txt";
    

    【讨论】:

    • 还是不行。它对你有用吗?你能运行它并检查一下吗?
    • ideone.com/DFmuu3(与wprintf())和ideone.com/DgzU2V(与printf())。不能将两者混合,因为第一个调用将 stdout 设置为使其与另一个不兼容的模式。
    • 我没有可以测试的 Windows 机器。我听说 Windows 库中缺少对 C99 的支持。不确定缺少什么。
    • @pmg: Microsoft's C94 implementation is non-conforming。 @RizvanFerdous 必须写 swprintf(NameBuffer,100,L"%hs",str1);(或类似的东西),因为 %s 需要 wchar_t,因为 swprintf() 是一个宽字符函数。看看this table。
    • 好吧,这些都不适合我。我想这样做的原因是因为我想用 + 替换字符串中的任何 空格,并使用新字符串使用 system (start www.example.com 打开 URL 例如,用户名: Rashed Ferdous 将从 Rashed Ferdous 转换为 Rashed+Ferdous 然后在这样的 URL 中使用: www.example.com/Rashed+Ferdous 所以代码看起来像: system (start www.example.com/Rashed+Ferdous); 有没有办法在不转换 wchar_t 字符串的情况下做到这一点?
    【解决方案2】:

    尝试使用 mbstowcs() 进行转换:

    #include <stdio.h>
    #include <wchar.h>
    #include <stdlib.h>
    
    int main(void)
    {
    
     wchar_t NameBuffer[100];
     char *str1 ="c:\\Program Files\\test.txt";
    
       mbstowcs(NameBuffer, str1, 100);
       wprintf(L"%ls\n",NameBuffer);
    
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 2012-05-30
      • 2015-02-27
      • 1970-01-01
      相关资源
      最近更新 更多