Ray's playground

 

Iostreams part2(Chapter 2 of Thinking in C++ Vol 2)

Effector
 1 #include <iostream>
 2 #include <cstdlib>
 3 #include <string>
 4 #include <climits>
 5 using namespace std;
 6 
 7 class Fixw
 8 {
 9     string str;
10 public:
11     Fixw(const string& s, int width) : str(s, 0, width){}
12     friend ostream& operator<<(ostream& os, Fixw& fw)
13     {
14         return os << fw.str;
15     }
16 };
17 
18 typedef unsigned long ulong;
19 
20 class Bin
21 {
22     ulong n;
23 public:
24     Bin(ulong nn) { n = nn; }
25     friend ostream& operator<<(ostream&, Bin&);
26 };
27 
28 ostream& operator<<(ostream& os, Bin& b)
29 {
30     ulong bit = ~(ULONG_MAX >> 1);
31     while(bit)
32     {
33         os << (b.n & bit ? '1' : '0');
34         bit >>=1;
35     }
36     return os;
37 }
38 
39 int main()
40 {
41     char* string = "Things that make us happy, make us wise";
42     for(int i=1; i<=strlen(string); i++)
43     {
44         cout << Fixw(string, i) << endl;
45     }
46 
47     ulong x = 0xCAFEBABEUL;
48     ulong y = 0x76543210UL;
49     cout << "x in binary: " << Bin(x) << endl;
50     cout << "y in binary: " << Bin(y) << endl;
51     cin.get();
52 }

 

posted on 2010-12-14 20:50  Ray Z  阅读(196)  评论(0编辑  收藏  举报

导航