473,804 Members | 2,112 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

From printf to C++ formatting

OK, I take back the nasty stuff I said about printf. At least until I see a
similarly concise way of writing this using C++ formatters. I want to
convert the following to something I can put onto a C++ std::ostream:

printf( " [%2x] %-20s %-8.8s %08x %06x %02x %-3.3s %02x %04x %02x\n",
i,
std::string( pSec->GetName() ).substr( 0, 20 ).c_str(),
SectionTypes( pSec->GetType() ).c_str(),
pSec->GetAddress() ,
pSec->GetSize(),
pSec->GetEntrySize() ,
SectionFlags( pSec->GetFlags() ).c_str(),
pSec->GetLink(),
pSec->GetInfo(),
pSec->GetAddrAlign () );

One option I've looked at, and may come back to, is the Boost.Format
library. For now, I want to see if I can find a reasonably elegant way of
using the C++ format manipulators. Does anybody have a systematic approach
to this kind of situation?
--
If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true.-Bertrand Russell
Aug 1 '05 #1
11 9820

Steven T. Hatton wrote:
OK, I take back the nasty stuff I said about printf. At least until I see a
similarly concise way of writing this using C++ formatters. I want to
convert the following to something I can put onto a C++ std::ostream:

printf( " [%2x] %-20s %-8.8s %08x %06x %02x %-3.3s %02x %04x %02x\n",
i,
std::string( pSec->GetName() ).substr( 0, 20 ).c_str(),
SectionTypes( pSec->GetType() ).c_str(),
pSec->GetAddress() ,
pSec->GetSize(),
pSec->GetEntrySize() ,
SectionFlags( pSec->GetFlags() ).c_str(),
pSec->GetLink(),
pSec->GetInfo(),
pSec->GetAddrAlign () );

One option I've looked at, and may come back to, is the Boost.Format
library. For now, I want to see if I can find a reasonably elegant way of
using the C++ format manipulators. Does anybody have a systematic approach
to this kind of situation?


With C++ io manipulators it would look ugly and much more error-prone
then a simple format string. The only trouble with printf is that it's
not type safe and it requires experience to know its pitfalls and use
it safely.

C++ standard streams and formatting are really clumsy.

Aug 2 '05 #2

Maxim Yegorushkin wrote:
With C++ io manipulators it would look ugly and much more error-prone
then a simple format string. The only trouble with printf is that it's
not type safe and it requires experience to know its pitfalls and use
it safely.

C++ standard streams and formatting are really clumsy.


That's why you can use boost::format which has the advantages of printf
and uses printf formatting, but also doesn't have the disadvantages of
the lack of type-safety and extensibility. (Extensibility in the type
of streams, not the type of data that can be given a formatting code).

(You can always extend your own objects to produce strings, of
different formats if required).

Aug 2 '05 #3

Steven T. Hatton wrote:
OK, I take back the nasty stuff I said about printf. At least until I see a
similarly concise way of writing this using C++ formatters. I want to
convert the following to something I can put onto a C++ std::ostream:

printf( " [%2x] %-20s %-8.8s %08x %06x %02x %-3.3s %02x %04x %02x\n",
i,
std::string( pSec->GetName() ).substr( 0, 20 ).c_str(),
SectionTypes( pSec->GetType() ).c_str(),
pSec->GetAddress() ,
pSec->GetSize(),
pSec->GetEntrySize() ,
SectionFlags( pSec->GetFlags() ).c_str(),
pSec->GetLink(),
pSec->GetInfo(),
pSec->GetAddrAlign () );

One option I've looked at, and may come back to, is the Boost.Format
library. For now, I want to see if I can find a reasonably elegant way of
using the C++ format manipulators. Does anybody have a systematic approach
to this kind of situation?


In this particular instance though you have a lot of calls to pSec. Now
you might want to keep this a free function rather than a member
function, and maybe the class is not your own.

However it is inflexible as you can only output to the console or
wherever the console is redirected to. Also are you always going to
output to this particular format or are you going to modify it? And
remember type-safety - if, for example, you allow users to pick their
own format string so they can output in different formats, and their
format string doesn't comply with your function, then it will still
compile beautifully but could go "bang!" when you run it.

pSec is obviously a pointer to something, and it can't be NULL, and
presumably it only reads and the class it reads from is const-correct
so I'd change from a pointer to a const reference.

Next, if you really feel you must output then use sprintf - at least
here you know how big a buffer you need, so then you can get your
function to return what you have constructed converting it to a
std::string. (But I would go with boost::format).

Alternatively, your function could take an ostream& parameter and
return it. If the user wants a string they will use ostringstream. If
this is the only way you are ever going to format the object then you
may as well make this

std::ostream & operator<<( std::ostream &, const Section & );

Assuming Section is the name of your class. (As the first element i is
probably unrelated you would stream that in separately).

Aug 2 '05 #4
If I were you I'd use boost.format :)

here's how:
#include <boost/format.hpp>

class pSec_Class {
...
...
friend std::ostream& opeartor<<
(std:ostream& os, const pSec_Class &x){
static boost::format frmt("your %1% format %2% string .?"
"some other vars?..");
os << frmt % x.GetType().c_s tr() % x.GetSize(); // ...
return os;
}
};

....
std::cout << *pSec << std::endl;

Aug 2 '05 #5
__PPS__ wrote:
If I were you I'd use boost.format :)

here's how:
#include <boost/format.hpp>

class pSec_Class {
...
...
friend std::ostream& opeartor<<
(std:ostream& os, const pSec_Class &x){
static boost::format frmt("your %1% format %2% string .?"
"some other vars?..");
os << frmt % x.GetType().c_s tr() % x.GetSize(); // ...
return os;
}
};

...
std::cout << *pSec << std::endl;


I probably should have worked through using the Boost.Format library. It
started looking a bit obscure when I tried to write it all out. What I
ended up doing was using brute force and C++ manipulators. It's not too
terribly ugly. I did create an operator<<() similar to what you show
above. Once I realized that there are two different things called `hex',
one being std::hex, and the other being ios_base::hex, and that one is a
value while the other is a function, things became much easier. That is a
gotch from hell. I couldn't figure out, for the life of me, why the
manipulator was not changing the format, but, instead, simply printing as a
numerical value.
--
If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true.-Bertrand Russell
Aug 2 '05 #6
As far as I remember boost.format supports printf-like syntax. Probably
you can do like this:
static boost format frmt("printf-like string");
....
read docs for boost.format

Aug 2 '05 #7
Steven T. Hatton a écrit :
OK, I take back the nasty stuff I said about printf. At least until I see a
similarly concise way of writing this using C++ formatters. I want to
convert the following to something I can put onto a C++ std::ostream:

printf( " [%2x] %-20s %-8.8s %08x %06x %02x %-3.3s %02x %04x %02x\n",
i,
std::string( pSec->GetName() ).substr( 0, 20 ).c_str(),
SectionTypes( pSec->GetType() ).c_str(),
pSec->GetAddress() ,
pSec->GetSize(),
pSec->GetEntrySize() ,
SectionFlags( pSec->GetFlags() ).c_str(),
pSec->GetLink(),
pSec->GetInfo(),
pSec->GetAddrAlign () );

One option I've looked at, and may come back to, is the Boost.Format
library. For now, I want to see if I can find a reasonably elegant way of
using the C++ format manipulators. Does anybody have a systematic approach
to this kind of situation?


Is not your purpose vain?
Formatting has been well done once with printf specifications.
I do not think that C++ formatters are intended to replace printf
formatting, but to allow a quick not-so-well formatted output.
But if you want to well control printing, it is easier to turn back to
printf-like formatting.
Please note that it is what MS has done with its CString::Format ()
Anyway, what seems to me missing is a bridge between printf-like
formatting and <string>.
Aug 4 '05 #9
Pierre Couderc wrote:
Steven T. Hatton a écrit :
OK, I take back the nasty stuff I said about printf. At least until I
see a similarly concise way of writing this using C++ formatters. I want
to convert the following to something I can put onto a C++ std::ostream:

printf( " [%2x] %-20s %-8.8s %08x %06x %02x %-3.3s %02x %04x %02x\n",
i,
std::string( pSec->GetName() ).substr( 0, 20 ).c_str(),
SectionTypes( pSec->GetType() ).c_str(),
pSec->GetAddress() ,
pSec->GetSize(),
pSec->GetEntrySize() ,
SectionFlags( pSec->GetFlags() ).c_str(),
pSec->GetLink(),
pSec->GetInfo(),
pSec->GetAddrAlign () );

One option I've looked at, and may come back to, is the Boost.Format
library. For now, I want to see if I can find a reasonably elegant way
of
using the C++ format manipulators. Does anybody have a systematic
approach to this kind of situation?


Is not your purpose vain?
Formatting has been well done once with printf specifications.
I do not think that C++ formatters are intended to replace printf
formatting, but to allow a quick not-so-well formatted output.
But if you want to well control printing, it is easier to turn back to
printf-like formatting.
Please note that it is what MS has done with its CString::Format ()
Anyway, what seems to me missing is a bridge between printf-like
formatting and <string>.


But how do you use printf with std::ostream? The biggest obstacle I've
found with the C++ formatters is that there is no way that I am aware of to
truncate with them.
--
If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true.-Bertrand Russell
Aug 4 '05 #10

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

Similar topics

11
55606
by: Pontus F | last post by:
Hi I am learning C++ and I'm still trying to get a grip of pointers and other C/C++ concepts. I would appreciate if somebody could explain what's wrong with this code: ---begin code block--- #include "stdio.h" #include "string.h" void printText(char c){
3
2461
by: Matt | last post by:
Hello, Is there a means to use printf()-like formatting (eg: http://www.mkssoftware.com/docs/man1/printf.1.asp ) using class string and/or iostream constructs so that I need not have to define fixed-size character buffers (like it appears that I have to do in printf()...or maybe there's an alternative)? -Matt --
8
20190
by: scrodchunk | last post by:
I'm having a weird problem with printing bytes in hex format. I have a bunch of print statements that are working okay, then using the identical formatting later in my code I get some thing where the formatting and type are ignored. At one spot in my code I'm loading an array with random bytes int i; char byte_block;
7
2557
by: sunfiresg | last post by:
During an interview, I am asked to answer a question: Printf is a major formatted output function provided by the standard C library. Printf accepts a formatting string followed by a various number of arguments to replace formatting specifiers in the formatting string. You should implement the subset of the printf function compliant to the following specification.
8
15500
by: jchludzinski | last post by:
Is there a format specification for printf that will result in: 1000000 being printed as 1,000,000? Or 1000000.0 as 1,000,000.0? ---John
27
2983
by: jacob navia | last post by:
Has anyone here any information about how arrays can be formatted with printf? I mean something besides the usual formatting of each element in a loop. I remember that Trio printf had some extensions but I do not recall exactly if they were meant for arrays. Thanks
36
35564
by: Debaser | last post by:
I've recently read in one of my old C books that puts() is a better function call with regard to performance than printf() in the following situation: puts("Some random text"); vs. printf("Some random text\n");
18
3778
by: Joah Senegal | last post by:
Hello all, I'm trying to print a string on my screen... But the string comes from a variable string... This is the code #include <cstdlib> #include <iostream> #include <string> using namespace std;
25
9735
by: jacob navia | last post by:
The C99 standard forgot to define the printf equivalent for complex numbers Since I am revising the lcc-win implementation of complex numbers I decided to fill this hole with "Z" for instance double _Complex m = 2+3*I; printf("%Zg\n",m);
0
10595
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
10343
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
10341
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
10089
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
9171
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
5530
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...
1
4308
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
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.