You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法向stringstream对象写入string?C++单词去重代码问题

C++句子单词去重问题:原代码错误分析与修复

原代码问题根源

你遇到的words << word不生效的核心原因是:
当while (words >> w)循环遍历完整个stringstream后,流的**eofbit(结束标志)**会被置位,流进入错误状态。此时所有后续的读写操作都会被直接忽略,自然无法写入新单词。

同时原代码还有两个隐含问题:

  1. 每次检查时没有将读指针重置到流开头,第二次调用函数时会直接跳过读取(因为指针停在流末尾)。
  2. 写入单词时没有添加分隔符,会导致单词连在一起,后续读取时无法区分。

原代码修复方案

修改is_there_any函数,处理流状态和指针位置:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

bool is_there_any(string word, stringstream& words)
{
    string w;
    // 将读指针移到流开头,确保每次都能读取所有已存储单词
    words.seekg(0);
    while (words >> w)
    {
        if (word == w)
            return true;
    }
    // 清除流的错误状态(eof/fail标志),恢复可写能力
    words.clear();
    // 将写指针移到流末尾,追加新单词而非覆盖
    words.seekp(0, ios::end);
    // 写入单词时添加空格作为分隔符
    words << word << " ";
    return false;
}

int main()
{
    string sentence, word;
    getline(cin, sentence);
    stringstream stream(sentence);
    stringstream words;
    
    while (stream >> word)
    {
        if (!is_there_any(word, words))
            cout << word << endl;
    }
    return 0;
}

更优实现方案:使用哈希集合去重

用std::unordered_set(哈希集合)替代stringstream存储已出现单词,代码更简洁且效率更高(查找/插入平均时间复杂度O(1)):

#include <iostream>
#include <sstream>
#include <string>
#include <unordered_set>

using namespace std;

int main()
{
    string sentence, word;
    getline(cin, sentence);
    stringstream stream(sentence);
    unordered_set<string> seen_words;

    while (stream >> word)
    {
        // 检查单词是否未出现过
        if (seen_words.find(word) == seen_words.end())
        {
            cout << word << endl;
            seen_words.insert(word);
        }
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Nadja Popovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:13:36