![](/img/trans.png)
[英]how to define macro to convert concatenated char string to wchar_t string in C
[英]How to copy/convert a char string to a wchar_t string in C?
我環顧四周,從<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;
}
這段代碼有什么問題嗎?還是我的編譯器?
在上面的代碼中,在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";
嘗試使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.