将一串单词解析成一组单词

时间:2015-03-27 05:45:31

标签: c++ parsing set stringstream

这是我正在编写的函数,用于将一串单词解析成一组单词。

std::set<std::string> parseStringToWords(string rawWord) 
{
    getline(cin,rawWord);
    std::set<std::string> myset;
    istringstream iss(rawWord);
    string word;
    while(iss >> word) {
        myset.insert(word);
    }
}

我很确定到目前为止我所拥有的是正确的,但我不确定在while循环中该做什么。任何提示?

1 个答案:

答案 0 :(得分:2)

这里有一些代码可以引导您朝着良好的方向发展:

#include <iostream>
#include <string>               // std::string
#include <set>                  // std::set
#include <sstream>              // std::istringstream

namespace my {
    using std::cin;
    using std::cout;
    using std::istringstream;
    using std::set;
    using std::string;

    auto set_of_words( const string& s )
        -> set<string>
    {
        set<string> result;
        istringstream iss( s );
        string word;
        while( iss >> word )
        {
            result.insert( word );
        }
        return result;
    }

    auto getline( const string& prompt )
        -> string
    {
        string result;
        cout << prompt;
        getline( cin, result );
        return result;
    }
}  // namespace my

auto main() -> int
{
    using namespace my;
    using namespace std;

    const set<string> words = set_of_words( getline( "A line of words, please: ") );
    cout << "You entered these unique_words:" << endl;
    for( const string word : words )
    {
        cout << "* " << word << endl;
    }
}

此代码的主要问题是它不会检查或处理故障。在专业工作中,大部分代码通常都与故障检查和处理有关。特别是my::getline函数不应该只在输入失败时静默返回结果。

另一个问题是由于缺乏抽象而缺乏可重用性。正如我在对问题的评论中已经提到的,对于经验丰富的程序员来说,自然的方法是让分词到单词函数将单词传递给输出迭代器。这样便于直接用于各种目的,例如在一行输出单词,或将它们添加到一组,或将它们放在向量的末尾,......;并且它便于为此目的编写便利包装。更重要的是,它的一般原则就是不要不必要地将自己约束到给定的数据表示。但另一方面,不要在有希望的概括上浪费工作,因为最终人们可能会发现它没有被使用。