2014-05-18 25 views
-1

在我的程序中,我讀取文本文件,然後小寫所有,並單獨分割它們並追加到字符串。計數字的出現

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++;} 
    } 
} 

我需要做的是計算一個單詞在文本文件中出現的次數。有點這樣做。但我需要它們以降序顯示。

+0

你爲什麼要使用這麼多的C 2這是一項要求嗎? – Chnossos

+2

我建議你檢查'std :: map'類型。你可以用這個詞作爲關鍵詞,把count作爲它的值。 (排序地圖很容易) – enhzflep

+0

@Chnossos這是我知道如何寫的方式。 – user1794625

回答

1

這裏是唯一考慮的話,並將它們打印按降序排列的完整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; 
}