0

cinでstdマニピュレーターを使用してパンクチャクションを無視することは可能ですか?たとえば、「1、2、3」のような入力ストリーム(実際にはファイル)があるとします。私ができるようになりたい:

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

最後a=="one"b=="two"、、c=="three"

4

2 に答える 2

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'; }
};

代わりにasを呼び出しgetline(std::cin, my_string, punct_or_newline())ます。お役に立てれば!

于 2010-10-13T23:19:08.180 に答える
1

これを試して:

ローカルを使用して句読点を除外します。
これにより、残りのコードを変更せずに残すことができます。

#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";
}
于 2010-10-14T00:02:17.310 に答える