【发布时间】:2017-04-27 07:23:00
【问题描述】:
我有一个程序,它获取一个文本文件并列出单词及其使用次数。它有效,但我不知道如何打印出文本文件。在排序后的单词及其出现的次数上方,我想显示文件中的文本。我该怎么做?我尝试了几件事,但它要么什么都不做,要么把剩下的代码搞砸了,说有 0 个唯一词。最后,如何打印出结果,使它们更... table -ish...
/*
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;
}
【问题讨论】:
-
请修正您的代码格式。您的打印看起来不错;您确定
words包含的数据正确吗? -
我修复了它,使其更易于阅读。我相信是这样。它给了我一些测试文件的正确答案。由于某种原因,我只是无法打印实际的文件内容。我试着把 'while(fin.good()) cout
-
我认为问题在于你试图读取输入文件两次(一次复制到输出,一次进入令牌)但你没有重置位置之间! 因此,第二次尝试将看到一个空文件。请参阅
clearandseekgcalls in this answer。或者,您可以尝试交错打印和标记,但除非文件非常大,否则可能不值得努力。
标签: c++