使用操纵器忽略标点符号

时间:2010-10-13 22:32:13

标签: c++ std manipulators

是否有可能在cin上使用std操纵器忽略punctuacion?例如,假设您有一个输入流(在实际情况下是一个文件),如:“一,二三”。我希望能够做到:

f >> ignore_punct >> a;
f >> ignore_punct >> b;
f >> ignore_punct >> c;

最后a=="one"b=="two"c=="three"

2 个答案:

答案 0 :(得分:1)

没有标准库的方法,但如果我理解正确的话,这很容易做到。如果你想读一个字符串直到一些标点符号就好像是换行符一样,那么你可以使用一个getline版本接受一个谓词而不是一个分隔符:

template<class F>
std::istream& getline(std::istream& stream, std::string& string, F delim) {

    string.clear();

    // Get characters while the stream is valid and the next character is not the terminating delimiter.
    while (stream && !delim(stream.peek()))
        string += stream.get();

    // Discard delimiter.
    stream.ignore(1);

    return stream;

};

用法示例:

#include <iostream>
#include <cctype>

int main(int argc, char** argv) {

    std::string s;
    getline(std::cin, s, ::ispunct);

    std::cout << s << '\n';
    return 0;

}

如果您还希望打破换行符,那么您可以编写一个仿函数:

struct punct_or_newline {
    bool operator()(char c) const { return ::ispunct(c) || c == '\n'; }
};

然后调用getline(std::cin, my_string, punct_or_newline())。希望这有帮助!

答案 1 :(得分:1)

试试这个:

它使用local来过滤掉标点符号 这允许其余代码保持不变。

#include <locale>
#include <string>
#include <iostream>
#include <fstream>
#include <cctype>

class PunctRemove: public std::codecvt<char,char,std::char_traits<char>::state_type>
{
    bool do_always_noconv() const throw()  { return false;}
    int do_encoding()       const throw()  { return true; }

    typedef std::codecvt<char,char,std::char_traits<char>::state_type> MyType;
    typedef MyType::state_type          state_type;
    typedef MyType::result              result;


    virtual result  do_in(state_type& s,
            const char* from,const char* from_end,const char*& from_next,
                  char* to,        char* to_limit,      char*& to_next  ) const
    {
        /*
         * This function is used to filter the input
         */
        for(from_next = from, to_next = to;from_next != from_end;++from_next)
        {
            if (!std::ispunct(*from_next))
            {
                *to_next = *from_from;
                ++to_next;
            }
        }
        return ok;
    }

    /*
     * This function is used to filter the output
     */
    virtual result do_out(state_type& state,
            const char* from, const char* from_end, const char*& from_next,
                  char* to,         char* to_limit,       char*& to_next  ) const
    { /* I think you can guess this */ }
};


int main()
{
    // stream must be imbued before they are opened.
    // Otherwise the imbing is ignored.
    //
    std::ifstream   data;
    data.imbue(std::locale(std::locale(), new PunctRemove));
    data.open("plop");
    if (!data)
    {
        std::cout << "Failed to open plop\n";
        return 1;
    }

    std::string         line;
    std::getline(data, line);
    std::cout << "L(" << line << ")\n";
}