我正在尝试使用C ++中的输入文件创建一个词典

时间:2011-04-11 16:32:19

标签: c++ lexicon

我有一个file.txt我想在C ++中创建一个可以读取该文件中的单词的函数,并将每个单词及其出现次数打印到file2.txt

我正在做一些研究我知道我可以使用解析器和编写器,还有地图类,请问有什么帮助吗?

bool Parser::hasMoreTokens() {
  if(source.peek()!=NULL){
    return true;
}
else{
     return false;
}
}

3 个答案:

答案 0 :(得分:3)

这是家里的工作吗?在线查看std::mapstd:stringstd::ifstreamstd::ofstream

答案 1 :(得分:1)

使用ifstream阅读文件,存储到mapstring中,使用int作为map的值,并在每次遇到具体string。接下来,使用ofstream将它们写入文件。

答案 2 :(得分:0)

如果您希望提高效率并以尽可能少的行数完成此任务,但使用标准库,请尝试以下操作:

#include <fstream>
#include <iostream>
#include <iterator>
#include <set>
#include <string>

int main()
{
     std::ifstream f("text.txt");
     std::istream_iterator<std::string> eof;
     std::multiset<std::string> words( std::istream_iterator<std::string>(f) , eof);

     std::ofstream f_out("text_output.txt");
     for( std::multiset<std::string>::iterator i = words.begin(); i!=words.end(); i = words.upper_bound(*i) )
          f_out << "the word " << *i << " found " << words.count(*i) << " times\n";

}

此代码获取名为“text.txt”的文件并将结果输出到“text_output.txt”

  • “text.txt”的内容:
    我可以这样做吗? 我需要多少次编程才能记住它?

  • “text_output.txt”的内容:
    单词如何找到1次
    这个词我发现了4次 这个词可以找到3次
    这个词确实发现了2次 这个词呢?发现1次
    许多人发现了1次这个词 这个词需要找到1次
    单词一找到1次
    单词程序找到1次
    这个词好吗?发现1次
    这个词记得1次发现 这个词发现了1次 这个词发现了1次 单词时间发现1次
    找到2次的单词

有效学习有效使用c ++的好方法是一本名为Accelerated c ++的书。

问候,