繁体   English   中英

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

[英]I am trying to create a lexicon using an input file in C++

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

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

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

这是家庭作业吗? 在线查找std::mapstd:stringstd::ifstreamstd::ofstream

使用ifstream读取文件,将其存储在字符串 s的map中,将int用作map值,并在每次遇到特定string时递增。 接下来,使用ofstream将它们写入文件。

如果您想提高效率并以较少的行数完成此操作,但是可以使用标准库,请尝试以下操作:

#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”的内容:
    III可以做到这一点吗?
    我需要编程几次才能记住一件事?

  • “ text_output.txt”的内容:
    单词如何找到1次
    我找到4次的单词
    这个词可以找到3次
    这个词确实发现了2次
    这个词吗? 找到1次
    这个词被发现多次
    这个词需要找到1次
    这个词被发现1次
    单词程序找到1次
    这个词正确吗? 找到1次
    这个词记得找到1次
    单词事物发现1次
    这个词找到1次
    单词times找到1次
    找到2次的单词

名为Accelerated c ++的书是学习有效使用c ++的绝妙方式的好资源。

问候,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM