【问题标题】:Using UTF-8 in C compiler在 C 编译器中使用 UTF-8
【发布时间】:2020-08-05 20:21:55
【问题描述】:

我是 C 编程新手,我有一个任务要做。我的作业就是这样:

假设您从键盘(您可能将其视为默认输入设备)逐个字符地扫描土耳其语输入文本,直到按下“CTRL-D”。您应该跳过标点符号和空白字符。只要扫描过程完成,您的程序就会显示字母和数字的频率。您需要讨论数据结构以及流程图解决方案并将它们与您的代码一起提交。

我编写了程序,但我遇到了问题。输入的某些字符(例如ğ)显示为§。这是我的源代码。

#include <stdio.h>
#include "stdlib.h"
#include <locale.h>


int main()
{
    char message[100] = { ' ' };
    char ch;
    int i = 0, j = 0, k = 0;

    setlocale(LC_ALL, "Turkish");

    printf("Enter your message: ");

    while ((ch = getchar()) != '\4')
    {
        message[i] = ch;
        i++;
    }

    for (int j = 0; j <= i; j++)
    {
        int repeated = 1;

        for (int k = (j + 1); k <= i; k++)
        {
            if (message[k] == message[j])
            {
                repeated++;
            }
        }
        printf("%c is repeated %d times.\n", message[j], repeated);
        while (message[j] == message[j + 1])
        {
            j = j + 1;
        }
    }

    system("PAUSE");
    return 0;
}

我该如何解决这个问题?

【问题讨论】:

    标签: c unicode utf-8 ascii


    【解决方案1】:

    ğ是一个多字节字符(占用2个字节),不能用%c打印,也不能算作普通字符(循环时必须跳过2个字节)。

    但是您不需要这样做,C 提供了处理多字节字符的库。

    你可以用wchar_t代替char,也可以用getwchar代替getchar,用printf代替wprintf,最后,注意所有字符串字面量都以L为后缀并打印字符使用%lc 格式说明符。

    你的代码工作:

    #include <stdio.h>
    #include <stdlib.h>
    #include <locale.h>
    #include <wchar.h>
    
    int main()
    {
        setlocale(LC_ALL, "");
    
        #define N 100
        wchar_t message[N];
        struct
        {
            wchar_t value;
            int count; 
        } letters[N] = {{0, 0}};
    
        wprintf(L"Enter your message:\n");
    
        wint_t ch;
        int len = 0;
    
        while ((ch = getwchar()) != '\n')
        {
            if (len < N)
            {
                message[len++] = ch;
            }
        }
    
        int n = 0;
    
        for (int i = 0; i < len; i++)
        {
            int j;
    
            for (j = 0; j < n; j++)
            {
                if (letters[j].value == message[i])
                {
                    break;
                }
            }
            if (j == n)
            {
                letters[j].value = message[i];
                n++;
            }
            letters[j].count++;
        }
        for (int i = 0; i < n; i++)
        {
            wprintf(L"%lc is repeated %d times.\n", letters[i].value, letters[i].count);
        }
        return 0;
    }
    

    【讨论】:

    • 谢谢大家,但我仍然有同样的问题。
    • 什么问题?您仍然看到 § 而不是 ğ
    • 是的。当我打印 ğ 时,我看到了 §.
    • @root_roxox 已编辑,现在代码可以满足您的要求:每个字母重复 1 次的次数
    • @David Ranieri 哦,谢谢。我试图纠正它,我几乎成功了,但我没有纠正最后一个字母的重复。多亏了你,我才能交出一份合适的作业。我欠你的。
    猜你喜欢
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    相关资源
    最近更新 更多