C++ 计算单词出现次数
在我的程序中,我读取文本文件,然后将它们全部小写,然后将它们单独拆分并附加到字符串中C++ 计算单词出现次数,c++,C++,在我的程序中,我读取文本文件,然后将它们全部小写,然后将它们单独拆分并附加到字符串中 using namespace std; int main() { int lines=0,i=0,k=0; FILE *pfile=fopen("myfile.txt", "r"); char line2[500]; char * tok; string alltext[999]; string words[999]; if(!pfile){printf("Error\n");return 1;} std
using namespace std;
int main() {
int lines=0,i=0,k=0;
FILE *pfile=fopen("myfile.txt", "r");
char line2[500];
char * tok;
string alltext[999];
string words[999];
if(!pfile){printf("Error\n");return 1;}
std::string line;
std::ifstream myfile("eriala.txt");
while (std::getline(myfile, line))
++lines;
for(i=0;i<lines;i++){
fgets(line2,sizeof(line2),pfile);
char * str = line2;
for (int i =0;i<strlen(line2); ++i){
line2[i]=tolower(line2[i]);}
tok = strtok(str," ,.!\n\t():;-");
while(tok !=NULL){
alltext[k].append(tok);
alltext[k].append("\n");
tok=strtok(NULL," ,.!\n\t():;-");
k++;}}
for(int i=0;i<k;i++){
int amount=0;
for(int j=0;j<k;j++){
if(strcmp(alltext[i].c_str(),alltext[j].c_str())==0)
amount++;}
}
}
使用名称空间std;
int main(){
int行=0,i=0,k=0;
FILE*pfile=fopen(“myfile.txt”、“r”);
charline2[500];
char*tok;
字符串alltext[999];
字符串[999];
如果(!pfile){printf(“Error\n”);返回1;}
std::字符串行;
std::ifstream myfile(“erila.txt”);
while(std::getline(myfile,line))
++线条;
对于(i=0;i,这里有一个完整的C++11版本,它计算单词并按降序打印:
#include <algorithm>
#include <cctype>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
int main ()
{
std::ifstream file ("myfile.txt"); // Try to open the file
if (!file)
{
std::cerr << "Error: Cannot open file myfile.txt" << std::endl;
return 1;
}
std::map<std::string, std::size_t> word_counter;
std::string word;
while (file >> word) // While a word can be read
{
// Remove every character that is not an alphanumeric one
word.erase(std::remove_if(std::begin(word), std::end(word), [](char c) { return !::isalnum(c); }), std::end(word));
if (!word.empty())
{
// Lower case the word
std::transform(std::begin(word), std::end(word), std::begin(word), ::tolower);
// Increment the counter for this word
word_counter[word]++;
}
}
// Print the counted words in descending order
for (auto it = word_counter.crbegin() ; it != word_counter.crend() ; ++it)
std::cout << it->first << " => " << it->second << std::endl;
}
#包括
#包括
#包括
#包括
#包括
#包括
int main()
{
std::ifstream文件(“myfile.txt”);//尝试打开该文件
如果(!文件)
{
std::cerr word)//当一个单词可以被读取时
{
//删除所有非字母数字字符
擦除(std::remove_if(std::begin(word),std::end(word),[](char c){return!::isalnum(c);}),std::end(word));
如果(!word.empty())
{
//字的小写字母
std::transform(std::begin(word)、std::end(word)、std::begin(word)、std::tolower);
//增加这个单词的计数器
字计数器[字]+;
}
}
//按降序打印计数的单词
用于(自动it=word_counter.crbegin();it!=word_counter.crend();++it)
std::cout首先你为什么要用这么多C?这是一个要求吗?我建议你检查一下std::map
类型。你可以用单词作为键,计数作为值。(对map排序很容易)@Chnossos这是我知道如何写的方法。