473,770 Members | 7,287 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

a question about overloading operator<<

I have a double that I want to output as: (depending on its value)

1000 Bytes
1.6 Kilobyte
2.5 Megabytes
..5 Terabytes

can I do this with...

ostream & operator<<(ostr eam & o, double n)
How would you recommend going about outputting this?
Jul 22 '05 #1
7 1650
JustSomeGuy wrote:
I have a double that I want to output as: (depending on its value)

1000 Bytes
1.6 Kilobyte
2.5 Megabytes
.5 Terabytes

can I do this with...

ostream & operator<<(ostr eam & o, double n)
No you cannot. Operators for standard types have been already defined.

How would you recommend going about outputting this?

Just make a wrapper around double:

class BytesFormat {
public:
BytesFormat( double d_ ) : d( d_ ) {}
friend std::ostream &operator<<( std::ostream &os, const BytesFormat
&bt );
private:
double d;
};

void foo()
{
double bytes;
// ...

std::cout << BytesFormat( bytes );
}
std::ostream &operator<<( std::ostream &os, const BytesFormat &bt )
{
if( bt.d < 1000.0 ) os << d << " Bytes";
// ...
return os;
}

--
Regards,
Slava

Jul 22 '05 #2
Vyacheslav Kononenko wrote:
JustSomeGuy wrote:
I have a double that I want to output as: (depending on its value)

1000 Bytes
1.6 Kilobyte
2.5 Megabytes
.5 Terabytes

can I do this with...

ostream & operator<<(ostr eam & o, double n)
No you cannot. Operators for standard types have been already

defined.

.... but still you can achieve the above goal! All you need to do is
to create a new "num_put" facet (i.e. a class derived from
'std::num_put<c har>'), install this facet into a 'std::locale' object,
and 'imbue()' the stream with the resulting object. There is no need
for falling back to ill-advised techniques.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting

Jul 22 '05 #3
Dietmar Kuehl wrote:
Vyacheslav Kononenko wrote:
JustSomeGuy wrote:
I have a double that I want to output as: (depending on its value)

1000 Bytes
1.6 Kilobyte
2.5 Megabytes
.5 Terabytes

can I do this with...

ostream & operator<<(ostr eam & o, double n)

No you cannot. Operators for standard types have been already


defined.

... but still you can achieve the above goal! All you need to do is
to create a new "num_put" facet (i.e. a class derived from
'std::num_put<c har>'), install this facet into a 'std::locale' object,
and 'imbue()' the stream with the resulting object. There is no need
for falling back to ill-advised techniques.


Cool. How about to print regular doubles and kilobytes at the same time? --
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting

--
Regards,
Slava

Jul 22 '05 #4
On Tue, 09 Nov 2004 09:46:56 -0500, Vyacheslav Kononenko
<vy********@NOk ononenkoSPAM.ne t> wrote:
Dietmar Kuehl wrote:
Vyacheslav Kononenko wrote:
JustSomeGu y wrote:

I have a double that I want to output as: (depending on its value)

1000 Bytes
1.6 Kilobyte
2.5 Megabytes
.5 Terabytes

can I do this with...

ostream & operator<<(ostr eam & o, double n)


No you cannot. Operators for standard types have been already


defined.

... but still you can achieve the above goal! All you need to do is
to create a new "num_put" facet (i.e. a class derived from
'std::num_put<c har>'), install this facet into a 'std::locale' object,
and 'imbue()' the stream with the resulting object. There is no need
for falling back to ill-advised techniques.


Cool. How about to print regular doubles and kilobytes at the same time?


You'd have to also write a manipulator to set a custom flag on the
stream and have the num_put facet obtain the formatting information
from the stream (in the ios_base& parameter) before deciding how to
output the number.

This is all a little involved, but you could write a reusable
framework to make it easier (and boost may have one already, just not
in a released version).

Tom
Jul 22 '05 #5
"Dietmar Kuehl" <di***********@ yahoo.com> wrote:
Vyacheslav Kononenko wrote:
JustSomeGuy wrote:
I have a double that I want to output as: (depending on its value)

1000 Bytes
1.6 Kilobyte
2.5 Megabytes
.5 Terabytes

can I do this with...

ostream & operator<<(ostr eam & o, double n)

No you cannot. Operators for standard types have been already

defined.

... but still you can achieve the above goal! All you need to do is
to create a new "num_put" facet (i.e. a class derived from
'std::num_put<c har>'), install this facet into a 'std::locale' object,
and 'imbue()' the stream with the resulting object.


You make it sound so easy :)
Jul 22 '05 #6
On 9 Nov 2004 11:41:24 -0800, ol*****@inspire .net.nz (Old Wolf) wrote:
"Dietmar Kuehl" <di***********@ yahoo.com> wrote:
Vyacheslav Kononenko wrote:
> JustSomeGuy wrote:
> > I have a double that I want to output as: (depending on its value)
> >
> > 1000 Bytes
> > 1.6 Kilobyte
> > 2.5 Megabytes
> > .5 Terabytes
> >
> > can I do this with...
> >
> > ostream & operator<<(ostr eam & o, double n)

> No you cannot. Operators for standard types have been already

defined.

... but still you can achieve the above goal! All you need to do is
to create a new "num_put" facet (i.e. a class derived from
'std::num_put<c har>'), install this facet into a 'std::locale' object,
and 'imbue()' the stream with the resulting object.


You make it sound so easy :)


There's definitely room for a boost library to make it easier, so that
you can, for example, just change the formatting of double without
having to worry about the other numeric types or formatting options,
etc.

Tom
Jul 22 '05 #7
Old Wolf wrote:
You make it sound so easy :)


That would be because it actually *is* easy! The only tricky part is
the actual formatting since the above is hardly a specification. Here
is some sample code:

| #include <locale>
| #include <iostream>
| #include <sstream>
| #include <algorithm>
|
| struct my_num_put:
| std::num_put<ch ar>
| {
| iter_type do_put(iter_typ e to, std::ios_base& fmt,
| char fill, long double d) const
| {
| std::ostringstr eam out;
| out.precision(1 );
| out << std::fixed;
| if (d < 1024.0)
| out << d << " Bytes";
| else if (d < 1024.0 * 1024.0)
| out << (d / 1024.0) << " Kilobytes";
| else if (d < 1024.0 * 1024.0 * 1024.0)
| out << (d / (1024.0 * 1024.0)) << " Megabytes";
| else if (d < 0.5 * 1024.0 * 1024.0 * 1024.0 * 1024.0)
| out << (d / (1024.0 * 1024.0 * 1024.0)) << " Gigabytes";
| else
| out << (d / (1024.0 * 1024.0 * 1024.0 * 1024.0))
| << " Terabytes";
|
| std::string const& s = out.str();
| return std::copy(s.beg in(), s.end(), to);
| }
| iter_type do_put(iter_typ e to, std::ios_base& fmt,
| char fill, double d) const
| {
| return do_put(to, fmt, fill, static_cast<lon g double>(d));
| }
| };
|
| int main()
| {
| std::locale loc;
| std::locale my_loc(loc, new my_num_put);
| std::cout.imbue (my_loc);
|
| std::cout << 1000.0 << "\n";
| std::cout << 1600.0 << "\n";
| std::cout << 2500000.0 << "\n";
| std::cout << 550000000000.0 << "\n";
| }

This is hardly rocket science...

Note a. that this code does indeed just what I decribed before and b.
most of the work goes into actually figuring out the right format. But
even then, it is no big deal.

BTW, if you want to have something like this which you could turn
on/off
at will, you would have to set formatting flags in the stream object to
tell the stream when you want which formatting. The location to store
e.g. a flag is in an 'int' object accessed using the stream's 'iword()'
object. However, this is no big deal either...
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting

Jul 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2035
by: Robert Wierschke | last post by:
Hi I want to overload the operator<< for a class Vector. class Vector { double x; double y; double z;
10
1656
by: pmatos | last post by:
Hi all, I have the following code: class test { public: test(const std::string *n) : name(n) {} virtual ~test() {} const std::string * getName() { return name; }
4
1516
by: bart.kowalski | last post by:
Hello, I'm trying to overload operator << for class CString, which has an operator const char *. I thought the following code would do: template <typename T> inline std::basic_ostream<T> operator<<( const std::basic_ostream<T>& p_Stream, const CString& p_String) {
8
8379
by: jois.de.vivre | last post by:
Hi, I'm having some trouble overloading the << operator. I have the following, very simple code: #include <iostream> using namespace std; class test { private: int val;
3
1658
by: Suresh Tri | last post by:
Hi all, I was trying to overload '<' operator for (varchar,varchar). But in the function which handles the comparision I want to use the previous '<' operator.. but it is going into a recursion. My simplified code looks like : create or replace function orastringcmp (varchar, varchar) returns boolean as 'declare
1
2134
by: atomik.fungus | last post by:
Hi, as many others im making my own matrix class, but the compiler is giving me a lot of errors related to the friend functions which overload >> and <<.I've looked around and no one seems to get the same error. Here is the code of the class template< class T > class Matrix { friend ostream &operator << <>( ostream &, const Matrix< T > & ); friend istream &operator >> <>( istream &, Matrix< T > & ); public: ...
6
1500
by: Peter v. N. | last post by:
Hi all, Maybe this has been asked a million times before. In that case I'm sorry for being to lazy to search the Internet or look it up in a decent C++ reference: I read in O'Reilly's C++ Pocket reference (see also http://www.oreilly.com/catalog/cpluspluspr/errata/ , btw not that bad), that the operator << has to be overloaded like this:
3
1730
by: johnmmcparland | last post by:
Hi all, I know it is possible to overload the operators and < in C++ but how can I do this. Assume I have a class Date with three int members, m_day, m_month and m_year. In the .cpp files I have defined the < and operators; bool Date::operator<(const Date& d) {
8
1729
by: Micko1 | last post by:
hi there, I have an issue when overloading <<. string operator << (room * &currentPlayerLocation); string room::operator << (room * &currentPlayerLocation) {
0
9592
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9425
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10230
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10058
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10004
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9870
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8886
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5313
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2817
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.