Напишите программу, которая читает и пишет логические значения (типа bool) в виде чисел, английских слов или слов любого другого языка по вашему выбору.
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 110 111 112 113 114 115 |
#include <iostream> using std::cout; using std::endl; using std::cin; 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 {true1,false1}; 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;//строковое представление для х 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(); //Если существует фасет Season_io, то вернуть поток с использованным фасетом и его функцией //виртуальной перегруженой to_str() 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(); 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 { string seasons[2]; public: US_season_io(string a="true",string b="false") { seasons[0]=a; seasons[1]=b; } const string& to_str(Season)const; bool from_str(const string&, Season&)const; //отсутствует US_season_id }; //const string US_season_io::seasons[]={"весна","лето","осень","зима"}; const string& US_season_io::to_str(Season x)const { if(x<true1||false1<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[true1]; const string* end=&seasons[false1]; const string* p=find(beg,end,s); if(p==end)return false; x=Season(p-beg); return true; } int main() { setlocale(LC_CTYPE,"Russian_Russia.1251"); Season x; cin >>x; cout <<x<<endl; locale loc(locale(),new US_season_io("Правда","Ложь")); cout.imbue(loc); cin.imbue(loc); cin >>x; cout <<x<<endl; return 0; } |
[youtube]https://www.youtube.com/watch?v=vDbMeMmyKJQ[/youtube]