首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用C++对文本文件中的重复项进行删除和计数

使用C++对文本文件中的重复项进行删除和计数,可以通过以下步骤实现:

  1. 打开文本文件:使用C++中的文件输入流(ifstream)打开要处理的文本文件。 示例代码:ifstream inputFile("filename.txt");
  2. 读取文件内容:使用C++中的getline()函数逐行读取文本文件的内容,并将每一行存储在一个字符串变量中。 示例代码:string line; while (getline(inputFile, line)) { // 处理每一行的内容 }
  3. 创建数据结构:使用C++中的数据结构,如哈希表(unordered_map)或红黑树(map)来存储每个单词的计数。 示例代码:unordered_map<string, int> wordCount;
  4. 处理每一行的内容:对于每一行读取的字符串,可以使用C++的字符串流(stringstream)将其分割为单词,并更新单词计数。 示例代码:stringstream ss(line); string word; while (ss >> word) { // 更新单词计数 wordCount[word]++; }
  5. 输出结果:遍历存储单词计数的数据结构,并将结果输出到文件或控制台。 示例代码:for (auto& entry : wordCount) { string word = entry.first; int count = entry.second; // 输出单词和计数 cout << word << ": " << count << endl; }

完整示例代码:

代码语言:txt
复制
#include <iostream>
#include <fstream>
#include <sstream>
#include <unordered_map>

using namespace std;

void removeDuplicatesAndCount(string filename) {
    ifstream inputFile(filename);
    if (!inputFile) {
        cout << "Failed to open file." << endl;
        return;
    }

    unordered_map<string, int> wordCount;
    string line;
    while (getline(inputFile, line)) {
        stringstream ss(line);
        string word;
        while (ss >> word) {
            wordCount[word]++;
        }
    }

    inputFile.close();

    for (auto& entry : wordCount) {
        string word = entry.first;
        int count = entry.second;
        cout << word << ": " << count << endl;
    }
}

int main() {
    string filename = "input.txt";
    removeDuplicatesAndCount(filename);

    return 0;
}

在上述示例代码中,我们使用了C++中的文件输入流(ifstream)来打开文本文件,并通过getline()函数逐行读取文件内容。然后,使用字符串流(stringstream)将每行字符串分割为单词,并使用unordered_map数据结构存储每个单词的计数。最后,遍历存储计数的unordered_map,并输出结果。

推荐的腾讯云相关产品:

  • 云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 云数据库 MySQL 版(CDB):https://cloud.tencent.com/product/cdb
  • 腾讯云对象存储(COS):https://cloud.tencent.com/product/cos
  • 人工智能(AI):https://cloud.tencent.com/product/ai
  • 腾讯云物联网(IoT):https://cloud.tencent.com/product/iot
  • 腾讯云移动开发(移动推送):https://cloud.tencent.com/product/mpns
  • 云原生应用引擎(TKE):https://cloud.tencent.com/product/tke

请注意,上述产品仅为示例,并非真实的推广内容。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

1分48秒

JSP库存管理系统myeclipse开发SQLServer数据库web结构java编程

1分34秒

JSP期末考试安排管理系统myeclipse开发mysql数据库web结构java编程

1分53秒

JSP贸易管理系统myeclipse开发mysql数据库struts编程java语言

1分3秒

JSP企业办公管理系统myeclipse开发SQLServer数据库web结构java编程

1分25秒

JSP票据管理系统myeclipse开发mysql数据库web结构java编程

1分28秒

JSP医药进销存管理系统myeclipse开发SQLServer数据库web结构java编程

27秒

JSP美容管理系统系统myeclipse开发mysql数据库web结构java编程

4分26秒

068.go切片删除元素

2分30秒

JSP SH论文答辩管理系统myeclipse开发mysql数据库mvc结构java编程

6分33秒

088.sync.Map的比较相关方法

5分8秒

084.go的map定义

9分32秒

075.slices库的6个操作

领券