#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
using namespace std;
string trim(string s){
if(s.empty())
return s;
s.erase(0,s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
return s;
}
void readTxt(string file){
std:map<std::string, int> newMap;
ifstream infile;
infile.open(file.data()); //将文件流对象与文件连接起来
char c;
infile >> noskipws; //不忽略空白字符,将其读取
string stopword = " ,;?.!0123456789";
string tmp = "";
while (!infile.eof())
{
infile >> c;
if(stopword.find(c) != string::npos){
tmp = trim(tmp);
if(tmp.length() == 0)
continue;
if(niuMap.count(tmp) > 0){
niuMap[tmp] += 1;
}
else{
niuMap.insert(map<string, int>::value_type (tmp, 1));
}
tmp = "";
}
else{
tmp += c;
}
}
infile.close(); //关闭文件输入流
for(auto it = newMap.begin(); it != newMap.end(); ++it){
cout << it->first << ":" << it->second << endl;
}
}
int main(){
string a;
cin >> a;
readTxt(a);
}
C++ 读取文件
最新推荐文章于 2025-06-05 13:15:11 发布
本文介绍了一个使用C++实现的文本处理程序,该程序能够读取文本文件,并统计除去特定停用词之外的单词出现频率。通过遍历文件内容并利用标准库中的数据结构进行词频统计,最后输出每个有效单词及其出现次数。
1331

被折叠的 条评论
为什么被折叠?



