尝试创建一个读取.txt文件,显示它,计数唯一单词的程序,并在使用了多少次的情况下显示独特的单词.C



我正在尝试创建一个读取.txt文件,显示它,计数唯一单词并在使用多少次旁边显示独特单词的程序。到目前为止,我拥有总唯一单词和所使用的独特单词的数量。我对如何计算每个单词使用的次数,而不仅仅是唯一单词的总体总数。我还将如何显示文件中的文本?我当前的打印语句将单词打印出显示的次数,我想将其更改为类似的内容:" AS:6"等...按字母顺序排列。任何建议或帮助将不胜感激。

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

要计算单词,使用 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]++要简单得多。

最新更新