c++ - Facet ctype, do_is() and specializations -
i derived ctype
class build own facet in order override virtual function do_is()
. purpose make stream extractor ignore space characters (and still tokenize on tabulation character). overriding calls implementation of mother class. compile wchar_t
. there no implementation of ctype::do_is()
char
template value. that's true gcc , vs 2010.
here code ; have uncomment 5th line test between 2 versions.
#include <iostream> #include <locale> #include <sstream> // #define wide_characters #ifdef wide_characters typedef wchar_t charactertype; std::basic_string<charactertype> in = l"string1\tstring2 string3"; std::basic_ostream<charactertype>& consoleout = std::wcout; #else typedef char charactertype; std::basic_string<charactertype> in = "string1\tstring2 string3"; std::basic_ostream<charactertype>& consoleout = std::cout; #endif struct csv_whitespace : std::ctype<charactertype> { bool do_is(mask m, char_type c) const { if ((m & space) && c == ' ') { return false; // space not classified whitespace } return ctype::do_is(m, c); // leave rest parent class } }; int main() { std::basic_string<charactertype> token; consoleout << "locale modified ctype:\n"; std::basic_istringstream<charactertype> s2(in); s2.imbue(std::locale(s2.getloc(), new csv_whitespace())); while (s2 >> token) { consoleout << " " << token << '\n'; } }
thank !
i did following code link give, , work.
#include <iostream> #include <vector> #include <locale> #include <sstream> // ctype facet declassifies spaces whitespace struct csv_whitespace : std::ctype<char> { static const mask* make_table() { // make copy of "c" locale table static std::vector<mask> v(classic_table(), classic_table() + table_size); // space not classified whitespace v[' '] &= ~space; return &v[0]; } csv_whitespace(std::size_t refs = 0) : ctype(make_table(), false, refs) {} }; int main() { std::string token; std::string in = "string1\tstring2 string3"; std::cout << "locale modified ctype:\n"; std::istringstream s(in); s.imbue(std::locale(s.getloc(), new csv_whitespace())); while (s >> token) { std::cout << " " << token << '\n'; } }
Comments
Post a Comment