读取和打印宽字符串

时间:2018-10-26 12:55:28

标签: c

嗨,我想阅读并打印c中宽字符的大写版本。 这是我的代码:

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

int main(){
    wchar_t sentence[100];
    setlocale(LC_ALL, "");

    void Edit(wchar_t str[]);

    printf("Enter sentence -> ");
    wscanf(L"%[^\n]ls", sentence);

    Edit(sentence);

    getchar();
    return 0;
}

void Edit(wchar_t str[]){
    int i = -1;
    while(str[++i])
        if(iswalpha(str[i]))    //get rid of whitespaces and other characters
            putwchar(towupper(str[i]));
}

如果我像这样初始化字符串,实际上问题似乎出在wscanf上:

wchar_t sentence[] = L"è";

然后在不读取或询问字符串的情况下对其进行编辑即可。

我正在使用Windows 10和美国国际键盘输入,因此要使其成为“è”,必须按`+ e。但是我也尝试用ctrl + v复制和粘贴它,但是不起作用。我在GCC编译器版本6.3.0中使用MINGW。我也在我的Macbook上尝试了此操作,但不起作用。

问题是,如果我输入“kèy”,我希望将“KÈY”作为输出。相反,我得到“ KSY”。我不知道为什么“è”输出“ S”,但是我尝试了其他人声,但得到了相同的随机字符。但是,如果将字符串初始化为“kèy”,则会得到“KÈY”。

更新

我将wscanf编辑为:

wscanf(L"%ls", sentence);

它可以在我的Macbook上使用,但不能在Windows上使用!同样,我也不能输入空格,因为wscanf停在第一个空格。

更新2

我发现了一些非常有趣的东西: 使用此代码段:

int main(){
    setlocale(LC_ALL, "");
    wchar_t frase[100];

    fwide(stdin, 1);
    wscanf(L"%ls", frase);
    wprintf(L"%ls", frase);

    return 0;
}

我发现this table,当我输入'è'时得到S,这是Win列所描述的。所以我尝试输入Þ,我得到了'è'!我认为问题出在cmd的代码上,我正在使用页面代码:850

我找到了解决方法 我用system("chcp 1252")来更改字符集,它起作用了!

1 个答案:

答案 0 :(得分:0)

不要使用fgetws来使用int main(){ wchar_t sentence[100]; setlocale(LC_ALL, ""); void Edit(wchar_t str[]); printf("Enter sentence -> "); fgetws(sentence,100,stdin); Edit(sentence); getchar(); return 0; } void Edit(wchar_t str[]){ int i = -1; while(str[++i]) if(iswalpha(str[i])) //get rid of whitespaces and other characters putwchar(towupper(str[i])); } -这将使您读取空白并防止缓冲区溢出。通常,它的最佳做法(尤其是在使用用户提供的输入时)可以防止缓冲区溢出。我在下面编辑了您的代码。

{{1}}

您可能还想定义缓冲区大小,并正确分配和释放内存。

相关问题