#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中的汉字及其出现的次数这个部分在控制台上是乱码?是哪里有出错嘛,真心求解了
不知道为什么 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;
}
wcout.imbue(locale("chs"));
先将输入文件用记事本打开,另存为UTF-16 LE编码的文本文件;然后让你的程序读这个另存为的文件。
你 cpp文件和 文本文件编码一致吗?
另外可以看看这个
https://blog.csdn.net/weixin_44488341/article/details/130288601
主要用到的函数——find函数:它是来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器。
//输入一个字符串,用map统计每个字符出现的次数并输出字符及对应的次数
void countStr_Char(string str){
//char是我们要统计的字符 int是字符出现的次数
map<char, int> count;
for(float i = 0;i<str.length();i++){
// 利用map的find函数来判断这个字符是否出现过
//find函数:如果map中没有要查找的数据,它返回的迭代器等于end函数
if(count.find(str[i])==count.end()){
//第一次出现,次数赋值为1
count[str[i]] = 1;
}
// 字符.次数++
else{count[str[i]]++;}
}
for(auto i:count){
cout<<i.first<<": "<<i.second<<" ";
}
cout<<endl;
}
main.cpp:
string str;
while (1) {
cin>>str;
countStr_Char(str);
}
输出:
asdsd
a: 1 d: 2 s: 2
dasds
a: 1 d: 2 s: 2
fdgfb
b: 1 d: 1 f: 2 g: 1
qqqqqqqqqqq
q: 11
weihanyan
a: 2 e: 1 h: 1 i: 1 n: 2 w: 1 y: 1