0
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <set>
#include <sstream>
#include <ctype.h>

using namespace std;

string GetLine() {
    string line;
    getline(cin, line);
    return line;
}
void OpenUserFile(ifstream& fileStream);
string GetFileContents(ifstream& file);
map<string, size_t> GenerateKeywordReport(string contents);

void OpenUserFile(ifstream& input)
{
    while(true) {
        cout << "Enter filename: ";
        string filename = GetLine();
        input.open(filename.c_str());
        if(input.is_open()) return;
        cout << "Sorry, I can't find the file " << filename << endl;
        input.clear();
    }
}

string GetFileContents(ifstream& input)
{
    string result;
    string line;
    while (getline(input,line)) {
        result+=line+"\n";
    }
    return result;
}

set<string> GetKeywords(){
    ifstream input("key.txt");
    set<string>result;
    string keywords;
    while(input >> keywords)
        result.insert(keywords);
    return result;
}

void PreprocessString(string& text)
{
    for (size_t k=0; k<text.size(); ++k) {
        if(ispunct(text[k]) && text[k]!='_')
            text[k]=' ';
    }
}

map<string,size_t> GenerateKeywordReport(string filecontent)
{
    map<string,size_t>result;
    set<string> keywords=GetKeywords();

    PreprocessString(filecontent);

    stringstream tokenizer ;
    tokenizer<<filecontent;

    string word;
    while(tokenizer>>word)
    {
        if(keywords.count(word))
            result[word]+=1;
    }
    return result;
}


int main(int argc, const char * argv[])
{
    ifstream input;
    OpenUserFile(input);

    map<string,size_t> report=GenerateKeywordReport(GetFileContents(input));

    for(map<string,size_t>::iterator itr=report.begin(); itr!=report.end(); ++itr)
        cout<<"Keyword "<<itr->first<<" appeared "<<itr->second<<" times."<<endl;
}

这是整个代码。它计算 cpp 文件中的关键字。该目录包含main.cpp、sample.cpp、key.txt。

Output::
Enter filename: sample.cpp
Sorry, I can't find the file sample.cpp

此代码取自 stanford cs106l Coursereader

上一章也有类似的代码(OpenUserFile()),它一直工作到昨天。

4

0 回答 0