我有一个程序可以获取一个文本文件并列出单词及其使用次数。它有效,但我不知道如何打印出文本文件。在排序的单词及其出现次数上方,我想显示文件中的文本。我该怎么做?我尝试了几件事,但它要么什么都不做,要么搞砸了代码的其余部分,说有 0 个独特的词。最后,如何打印出结果,使它们更……表格化……
/*
Something like this:
Word: [equal spaces] Count:
ask [equal spaces] 5
anger [equal spaces] 3
*/
感谢您能为我提供的任何帮助。
#include <iterator>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <cctype>
using namespace std;
string getNextToken(istream &in) {
char c;
string ans="";
c=in.get();
while(!isalpha(c) && !in.eof())//cleaning non letter charachters
{
c=in.get();
}
while(isalpha(c))
{
ans.push_back(tolower(c));
c=in.get();
}
return ans;
}
string ask(string msg) {
string ans;
cout << msg;
getline(cin, ans);
return ans;
}
int main() {
map<string,int> words;
ifstream fin( ask("Enter file name: ").c_str() ); //open an input stream
if( fin.fail() ) {
cerr << "An error occurred trying to open a stream to the file!\n";
return 1;
}
string s;
string empty ="";
while((s=getNextToken(fin))!=empty )
++words[s];
while(fin.good())
cout << (char)fin.get(); // I am not sure where to put this. Or if it is correct
cout << "" << endl;
cout << "There are " << words.size() << " unique words in the above text." << endl;
cout << "----------------------------------------------------------------" << endl;
cout << " " << endl;
for(map<string,int>::iterator iter = words.begin(); iter!=words.end(); ++iter)
cout<<iter->first<<' '<<iter->second<<endl;
return 0;
}
最佳答案
我会像这样使用一个简单的 for 循环:
for (int x = 0; x < words.size(); x++){
cout >> words[x] << endl
}
然后从那里修改以获得您想要的格式。 不过我确实注意到,您没有在上述代码的所有路径中返回 main 的值,这应该会产生编译时错误,但由于某种原因在我编译时却没有。我会提醒你,你需要有一个 main 的返回值。除非我误解了你的问题。如果没有创建示例文件,我无法运行该程序,因此如果没有额外的工作就无法对其进行测试。但是程序确实编译了。我没想到,因为缺少 return 语句。如果您无需我创建单词示例文件就可以重现您的错误,将单词列表插入代码并以最低限度重现错误,我将能够更好地帮助您。事实上,我希望我对你有所帮助。
关于c++ - 在程序 C++ 中发出打印 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43651157/