我正在尝试创建一个程序,该程序读取.txt文件,显示它,计算唯一单词并在使用的次数旁边显示唯一的单词。到目前为止,我有总的唯一单词数和使用的唯一单词。我有点不知道如何计算每个单词的使用次数而不仅仅是单个单词的总数。我如何显示文件中的文本?我当前的print语句打印出它出现的次数,我想把它改成这样的东西:“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;
}
答案 0 :(得分: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]++
要简单得多。