辞辞辞辞歌 2023-06-28 11:34 采纳率: 85.7%
浏览 74
已结题

c++对于文件中汉字的频次统计问题


#include<iostream>
#include<string>
#include<vector>
#include<fstream>
#include<map>
using namespace std;
int main() {
    wifstream ifs;
    vector<wchar_t>text;//存储文章
    map<wchar_t, int>all;
    map<wchar_t, int>::iterator p;


    ifs.open("附件.txt", ios::in);
    if (!ifs.is_open()) {
        cout << "文件打开失败" << endl;
        return -1;
    }


    int times = 0;
    wchar_t c;
    while (ifs.get(c)) {
        text.push_back(c);
    }
    for (int i = 0; i < text.size(); i++) {
        for (int n = 0; n < text.size(); n++) {
            if (text[i] >= 128) {//判定是否为中文字符
                if (text[i] == text[n]) {
                    times++;
                }
            }
        }
        all[text[i]] = times;//将中文字符及出现的频次保存在map中
        wcout << text[i];//输出文章
        times = 0;
    }
    
    system("pause");


    for (p = all.begin(); p != all.end(); p++) {
        wcout << p->first << ":" << p->second << endl;//输出map中的汉字及其出现的次数
    }


    ifs.close();
    return 0;
}

为什么这个代码输出map中的汉字及其出现的次数这个部分在控制台上是乱码?是哪里有出错嘛,真心求解了

img

  • 写回答

4条回答 默认 最新

  • 关注

    不知道为什么 system命令会干扰宽字符输出

    #include <fstream>
    #include <iostream>
    #include <locale>
    #include <map>
    #include <string>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
        wifstream ifs;
        ifs.imbue(locale(""));
        wcout.imbue(locale(""));
        vector<wchar_t> text; // 存储文章
        map<wchar_t, int> all;
    
        ifs.open(L"E:\\clangC++\\answer\\C++\\附件.txt", ios::in);
        if (!ifs.is_open())
        {
            wcout << L"文件打开失败" << endl;
            return -1;
        }
    
        int times = 0;
        wchar_t c;
        while (ifs.get(c))
        {
            text.push_back(c);
        }
        for (int i = 0; i < text.size(); i++)
        {
            for (int n = 0; n < text.size(); n++)
            {
                if (text[i] >= 128)
                { // 判定是否为中文字符
                    if (text[i] == text[n])
                    {
                        times++;
                    }
                }
            }
            all[text[i]] = times; // 将中文字符及出现的频次保存在map中
            wcout << text[i];     // 输出文章
            times = 0;
        }
    
        getchar();
    
        for (auto &&p : all)
        {
            wcout << p.first << L":" << p.second
                  << L"\n"; // 输出map中的汉字及其出现的次数
        }
    
        ifs.close();
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 7月7日
  • 已采纳回答 6月29日
  • 创建了问题 6月28日