Определите Season_io (параграф D.3.2) для языка отличного от американского английского.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
#include <iostream> using std::cout; using std::cin; using std::endl; using std::ostream; using std::istream; using std::ios_base; #include <locale> using std::locale; using std::has_facet; using std::use_facet; #include <string> using std::string; #include <algorithm> using std::find; enum Season {spring, summer, fall, winter}; class Season_io : public locale::facet { public: Season_io(int i=0):locale::facet(i){} ~Season_io(){}//обеспечивает возможность уничтожения объектов Season_io virtual const string& to_str(Season x)const =0;//строковое представление для x //place Season corresponding to s in x virtual bool from_str(const string& s, Season& x)const =0; static locale::id id;//объект идентификации фасета }; locale::id Season_io::id;//определяем идентифицирующий объект ostream& operator<<(ostream& s, Season x) { const locale& loc=s.getloc();//извлекаем stream's locale if(has_facet<Season_io>(loc)) return s <<use_facet<Season_io>(loc).to_str(x); return s <<int(x); } istream& operator>>(istream& s, Season& x) { const locale& loc=s.getloc();//извлекаем stream's locale if(has_facet<Season_io>(loc))//читаем алфавитное представление { const Season_io& f=use_facet<Season_io>(loc); string buf; if(!(s>>buf&&f.from_str(buf,x)))s.setstate(ios_base::failbit); return s; } int i;//читаем числовое представление s >>i; x=Season(i); return s; } class US_season_io:public Season_io { static const string seasons[]; public: const string& to_str(Season) const; bool from_str(const string&, Season&)const; //обратите внимание отсутствие US_season_io::id }; const string US_season_io::seasons[]={"spring","summer","fall","winter"}; const string& US_season_io::to_str(Season x) const { if(x<spring||winter<x) { static const string ss="no-such-season"; return ss; } return seasons[x]; } bool US_season_io::from_str(const string& s, Season& x) const { const string* beg=&seasons[spring]; const string* end=&seasons[winter]+1; const string* p=find(beg,end,s); if(p==end)return false; x=Season(p-beg); return true; } int main() { Season x; //Используем локализацию по умолчанию (нет фасета Season_io)-ввод вывод целых cin >>x; cout <<x<<endl; locale loc(locale(),new US_season_io); cout.imbue(loc);//используем локализацию с фасетом Season_io cin.imbue(loc);//используем локализацию с фасетом Season_io cin >>x; cout <<x<<endl; return 0; } |
[youtube]https://www.youtube.com/watch?v=Bi9c_xmznvo[/youtube]