2017-04-27 40 views
1

我正在嘗試創建一個讀取.txt文件,顯示它,計算唯一字並在顯示次數旁邊顯示唯一字的程序。到目前爲止,我有唯一的單詞總數和使用的獨特詞彙。我有點卡在如何計算每個單詞被使用的次數,而不僅僅是唯一單詞的總體總數。我如何顯示文件中的文本?我當前的打印語句顯示出現次數這個詞,我想將它改爲如下所示:「as:6」等...按字母順序排列。任何建議或幫助,將不勝感激。嘗試創建一個讀取.txt文件的程序,顯示它,對唯一字進行計數,並在使用次數旁邊顯示唯一字。 C++

#include <algorithm> 
#include <cctype> 
#include <string> 
#include <set> 
#include <fstream> 
#include <iterator> 
#include <iostream> 
using namespace std; 

string ask(string msg) { 
string ans; 
cout << msg; 
getline(cin, ans); 
return ans; 
} 

int main() { 
ifstream fin(ask("Enter file name: ").c_str()); //open an input stream on 
the given file 
if(fin.fail()) { 
    cerr << "An error occurred trying to open the file!\n"; 
    return 1; 
} 

istream_iterator<string> it{fin}; 
set<std::string> uniques; 
transform(it, {}, inserter(uniques, uniques.begin()), 
    [](string str) // make it lower case, so case doesn't matter anymore 
    { 
     transform(str.begin(), str.end(), str.begin(), ::tolower); 
     return str; 
    }); 

cout << "" << endl; 
cout << "There are " << uniques.size() << " unique words in the above text." << endl; 
cout << "----------------------------------------------------------------" << endl; 
cout << " " << endl;  

// display the unique elements 
for(auto&& elem: uniques) 
    for (int i=0; i < uniques.size(); i++) 
     cout << " " << elem << endl;  


// display the size: 
cout << std::endl << uniques.size(); 
return 0; 

} 
+4

*我有點卡在如何計算每個單詞的使用次數* - 考慮使用'std :: map '而不是'std :: set '。 – PaulMcKenzie

+1

如果我給了你一本書,並要求你計算每個單詞有多少次出現,你會怎麼做?根據需要,您可以獲得儘可能多的紙張。現在用英文描述解決問題的步驟。做這個練習將幫助你理解如何編寫代碼來解決問題或修復你到目前爲止的代碼。 –

回答

2

來算的話,用map<string, int>

map<string, int> mapObj; 
string strObj = "something"; 
mapObj[strObj] = mapObj[strObj] + 1 

同時顯示文字和計數值

for (auto & elem : mapObj) { 
    cout << elem.first << ": " << elem.second << endl; 
} 

編輯:由於PaulMcKenzie建議,mapObj[strObj]++要簡單得多。

+1

使用'map'非常簡單:'mapObj [strObj] ++;' – PaulMcKenzie

+0

我明白了。謝謝。我需要單獨提出另一個問題 – rcwade93

+0

@PaulMcKenzie你說得對,我只是將自己與Python中的'dict'搞混了,這可能會引發KeyError。謝謝! – Lodour

相關問題