我有一个程序需要一个文本文件并列出这些文字以及它们被使用了多少次。它的工作原理,但我不知道如何打印出文本文件。在排序的单词上方以及它们出现的次数之上,我想显示文件中的文本。我会怎么做?我尝试了几件事情,但它没有做任何事,或者把代码的其余部分搞砸,说有0个独特的词。以及最后如何将结果打印出来,使他们有更多...表-ish ...在C++程序中打印.txt文件
/*
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;
}
请修复您的代码的格式。你的印刷看起来不错,你确定数据'单词'包含的是正确的吗? –
我修好了,所以更容易阅读。我相信是这样。它给了我几个测试文件的正确答案。出于某种原因,我无法获得打印的实际文件内容。我试图把'while(fin.good())cout <<(char)fin.get();几个不同的地方,它搞砸了其余的代码。 – rcwade93
我认为问题在于你试图读取输入文件两次(一次复制到输出,一次打破令牌)_但你没有重置位置!_因此,第二次尝试将看到一个空文件。请参阅[在此答案中清除'和'seekg'调用](http://stackoverflow.com/a/7681612/2096401)。或者,您可以尝试交错打印和令牌化,但除非文件非常大,否则可能不值得。 – TripeHound