首页 > 解决方案 > 如何用c语言打印“∩”?

问题描述

我想在 C 中打印交点符号(∩),但它在ASCII 表中不存在。问题是我尝试的每件事都会产生一些奇怪的废话输出,比如 Ôê®。

起初我试着把它放在 printf 函数上:

#include <stdio.h>
int main(void)
{
    printf("∩");
    return 0;
}

在那之后不起作用,我在互联网上搜索了字符编码并在这里找到了它,所以我决定尝试这个:

#include <stdio.h>
int main(void)
{
    printf("\xE2\x88\xA9");
    return 0;
}

它仍然没有工作。经过更多研究,我认为更改语言环境会对我有所帮助,我尝试这样做:

#include <locale.h>
#include <stdio.h>
int main(void)
{
    setlocale(LC_ALL, "UTF-8");
    printf("\xE2\x88\xA9");
    return 0;
}

我也试过这个:

#include <locale.h>
#include <stdio.h>
int main(void)
{
    setlocale(LC_ALL, "");
    printf("\xE2\x88\xA9");
    return 0;
}

然后我尝试了这个:

#include <locale.h>
#include <stdio.h>
int main(void)
{
    setlocale(LC_ALL, NULL);
    printf("\xE2\x88\xA9");
    return 0;
}

然后我在互联网上找到了一些页面(不幸的是我忘记了它在哪里,再也找不到了)告诉我使用一个名为 wprintf 的函数,我这样做了:

#include <locale.h>
#include <wchar.h>
#include <stdio.h>
int main(void)
{
    setlocale(LC_ALL, "UTF-8");
    wprintf(L"\xE2\x88\xA9");
    return 0;
}

前面的所有代码都产生相同的输出:

Ôê®

如果有人可以帮我打印“∩”字符,我将不胜感激。

编辑:正如建议的那样,我尝试使用 windows.h 中的函数将代码页设置为我需要的,但它仍然只适用于代码编辑器:

#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#include <stdio.h>
#include <windows.h>

#if defined(_WIN32) 
    #define W 1
#else 
    #define W 0
#endif

int main(void)
{
    setlocale(LC_ALL, "UTF-8");

    if (W) // If the OS is windows
    {
        SetConsoleOutputCP(CP_UTF8);
        wprintf(L"\xE2\x88\xA9\n");
        SetConsoleOutputCP(850); // Set it back to normal to print other stuff later
    }

    return 0;
}

就像我说的那样,我的评论中所述的问题仍然存在,它适用于代码编辑器,但每当我在 winows 命令提示符下运行它时都不会。

标签: cutf-8character-encodingspecial-characters

解决方案


推荐阅读