我正在嘗試創建一個讀取.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;
}
*我有點卡在如何計算每個單詞的使用次數* - 考慮使用'std :: map'而不是'std :: set '。 –
PaulMcKenzie
如果我給了你一本書,並要求你計算每個單詞有多少次出現,你會怎麼做?根據需要,您可以獲得儘可能多的紙張。現在用英文描述解決問題的步驟。做這個練習將幫助你理解如何編寫代碼來解決問題或修復你到目前爲止的代碼。 –