Question

I'm trying to overload operator >> to accept various separators. I tried but could not.

Someone must know the solution?

My approach does not work.

template<typename A>
istream& operator >> (istream& is, const A& record) {
        is >> record;
        is.ignore(1, ',');
        return is;
}  

E.g. input:

1;2
3;4
5;6
7;8

Or

1,2
3,4
5,6
7,8

...

Note: I found some answers in the forum, but didn't help me.

Was it helpful?

Solution

You can't overload the input operator to work, e.g., with int. I'm not entirely sure what you want to achieve exactly but one way you could possibly deal with the unwanted separators is to turn them into magically into spaces! Let's assume you try to read the data with a loop like

for (int a, b; std::cin >> a >> b; ) {
    std::cout << "a=" << a << " b=" << b << "\n";
}

All what is really needed is that the separate is treated like space and skipped. To do so, you can use a custom std::ctype<char> facet:

#include <algorithm>
#include <iostream>
#include <locale>

struct ctype
    : std::ctype<char>
{
    typedef std::ctype<char> base;
    static base::mask const* make_table(unsigned char space,
                                        base::mask* table)
    {
        base::mask const* classic(base::classic_table());
        std::copy(classic, classic + base::table_size, table);
        table[space] |= base::space;
        return table;
    }
    ctype(unsigned char space)
    : base(make_table(space, table))
    {
    }
    base::mask table[base::table_size];
};

int main()
{
    std::locale global;
    std::locale loc(global, new ctype(';'));
    std::cin.imbue(loc);
    for (int a, b; std::cin >> a >> b; ) {
        std::cout << "a=" << a << " b=" << b << "\n";
    }
}

NOTE: I tried to compile this code with gcc on a Mac and it fails! The cause is actually not in the program but the problem is that std::ctype<char>::classic() returns a null pointer. I have no idea what that is about. Compiling with clang and libc++ works, however.

OTHER TIPS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top