473,372 Members | 1,293 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,372 software developers and data experts.

formatted output question with strings

Hi all,

I was wondering how I can perform formatted output with C++ strings. For
example, suppose I have in plain C:

sprintf(C_string, "%5.2f %6d");

How can I do such a thing with C++ strings? Using a string stream and
the << operator does not give me the formatting control like sprintf. Or
did I miss something.... :-|

Jeroen
Jul 23 '07 #1
6 3661
Jojo <no*****@thanx.comwrites:
>Hi all,
>I was wondering how I can perform formatted output with C++ strings. For
example, suppose I have in plain C:
sprintf(C_string, "%5.2f %6d");
???
>Or did I miss something.... :-|
Look up fill, width, adjustfield, setprecision, floatfield etc. E.g.

cout << 1331 <<endl;
cout << "In hex " << hex<< 1331 <<endl;

cout << 1331.123456 <<endl;
cout.setf(ios::scientific,ios::floatfield);
cout <<1331.123456 <<endl;
cout << setprecision(3) << 1331.123456 <<endl;
cout << dec << 1331 <<endl;
cout.fill('X');
cout.width(8);
cout << 1331 <<endl;
cout.setf(ios::left,ios::adjustfield);
cout.width(8);
cout << 1331 <<endl;

Jul 23 '07 #2
Tim Love schreef:
Jojo <no*****@thanx.comwrites:
>Hi all,
>I was wondering how I can perform formatted output with C++ strings. For
example, suppose I have in plain C:
> sprintf(C_string, "%5.2f %6d");
???
I was a bit in a hurry, I forgot the numeric arguments...
>
>Or did I miss something.... :-|
Look up fill, width, adjustfield, setprecision, floatfield etc. E.g.

cout << 1331 <<endl;
cout << "In hex " << hex<< 1331 <<endl;

cout << 1331.123456 <<endl;
cout.setf(ios::scientific,ios::floatfield);
cout <<1331.123456 <<endl;
cout << setprecision(3) << 1331.123456 <<endl;
cout << dec << 1331 <<endl;
cout.fill('X');
cout.width(8);
cout << 1331 <<endl;
cout.setf(ios::left,ios::adjustfield);
cout.width(8);
cout << 1331 <<endl;
I'll look that up. At first glance, the C++ method seems much less
'comprehensive' than sprintf. But I think it's better for me to get rid
of my plain-C habits when coding C++ :-)

Thanx,

Jeroen
Jul 23 '07 #3
Jojo wrote:
I'll look that up. At first glance, the C++ method seems much less
'comprehensive' than sprintf. But I think it's better for me to get rid
of my plain-C habits when coding C++ :-)
The C-style format string functions are compact, relatively easy
to learn and remember, and fast. Once you get the hang of them, it's
very easy to perform relatively complex formatting with a very small
amount of code which only takes a small amount of time to write.
Also, you never need to worry if some formatting setting "leaks" or
not (ie. if the stream will "remember" that setting or forget about
it immediately after printing the value).
The C++-style printing functions are much more verbose, and a
complex C one-liner can easily become over a dozen of lines of C++
(or, alternatively, a dozen of << operator calls in a row) using
diverse function names from <iostreamand <iomanip>. In some cases
it also feels a bit inconsistent whether some stream setting is
remembered or forgotten between << operator calls. Most are forgotten,
but some are remembered, causing potential "formatting leaks".

On the other hand:

C-style printing functions lack abstraction, which is the whole point
in the C++-style ones. For example, assume you have this:

typedef int MyIndex;
....
// Somewhere else:
MyIndex index;
....
std::printf("The value is: %i\n", index);

The printf() breaks the abstraction of 'MyIndex' because it assumes
it's an int. If you later change the typedef to:

typedef long MyIndex;

the printf() will break if long is larger than int (which is usually
the case in 64-bit systems). Even if the compiler is so smart as to
warn you about the incompatible printf format string, it could still
be tedious to go and change every single printf which uses that type
(which is something you wanted to avoid doing by using the typedef
in the first place).

Getting around this problem can be done, in a limited way, with all
kinds of awkward kludges, such as:

typedef int MyIndex;
#declare MyIndexFormatString "%i"
....
std::printf("The value is: " MyIndexFormatString "\n", index);

Of course this breaks immediately if you change MyIndex to something
not supported by printf(), such as a class.

Naturally you could try to avoid this problem by writing a function
for the only purpose of printing your MyIndex, like this:

void printMyIndex(MyIndex value);
....
std::printf("The value is: ");
printMyIndex(index);
std::printf("\n");

But this has two problems: You already lost the advantage over
the C++-way (ie. compactness), and you can't specify the formatting
for printing the value anylonger. You would have to add even more
kludges to this if you wanted to be able to specify the formatting:

void printMyIndex(MyIndex value, const char* format);
....
std::printf("The value is: ");
printMyIndex(index, "05");
std::printf("\n");

Of course if you wanted that width parameter to be defined by
a variable instead of being a string literal, it would become even
more complicated and awkward. The more you develop this further,
the more you are actually re-implementing C++ printing functions.

Also, the lack of abstraction causes a really bad breakdown with
templates. Consider:

template<typename T>
void print(const T& value)
{
std::printf("???", value); // What to write here???
}

The big advantage of C++-style printing is that it's abstract.
You don't have to worry about types. For example:

std::cout << index << std::endl; // I don't care what 'index' is.

Or:

template<typename T>
void print(const T& value)
{
std::cout << T << std::endl; // It doesn't matter what T is.
}

If you create your own class and you want to support printing it
in the regular way, you can! So it's perfectly possible to do this:

class MyIndex { ... };
....
MyIndex index;
....
std::cout << index << std::endl;

That MyIndex could be an int, a long, a double, a string or your
own Class, it doesn't matter. You don't have to specify the type
explicitly in the printing command, unlike in C.
Jul 23 '07 #4
On Jul 23, 9:39 am, Jojo <no_m...@thanx.comwrote:
I was wondering how I can perform formatted output with C++ strings. For
example, suppose I have in plain C:
sprintf(C_string, "%5.2f %6d");
How can I do such a thing with C++ strings?
To do exactly the above is a bit awkward, since you need several
manipulators. But normally, you only do something like the
above because C doesn't offer any alternative. What is the
first argument? What is the second? What semantic
characteristic does the first have which means that it should be
formatted using %5.2f, for example. In C++, you define the
formatting for such semantic characteristics, then write
something like:

... << ItsAToto << totosValue << ...

Something like ItsAToto is called a manipulator. Anytime you
write an application, you define the logical manipulators for
the various semantics that you want to support on output. That
way, if the request comes that all Toto now have to be output
with three digits after the decimal, you just change the
manipulator.

Note that most of the time, you're not outputting int's or
double's, but user defined types, which already have a specific
application dependant semantic. In such cases, the type of
"totosValue" says it all, and you don't need the manipulator.

(In text processing, this is known as logical mark-up. Roughly
speaking: C requires you to specify the physical mark-up,
locally, at each output site. C++ allows you to define a style
sheet.)
Using a string stream and
the << operator does not give me the formatting control like sprintf.
It gives you a lot more.
Or did I miss something.... :-|
If you're not familiar with maniipulators, or user defined
operator<<, you've missed practically all of iostream. (The
third important point is user defined streambufs.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jul 24 '07 #5
On Jul 23, 12:45 pm, Juha Nieminen <nos...@thanks.invalidwrote:
Jojo wrote:
I'll look that up. At first glance, the C++ method seems much less
'comprehensive' than sprintf. But I think it's better for me to get rid
of my plain-C habits when coding C++ :-)
The C-style format string functions are compact, relatively easy
to learn and remember, and fast.
They're compact. That's all you can say for them. They're
very, very limited in what they can do, however, and they're
very, very low level, and don't support higher level
abstractions. They also quite exoteric; even after 25 years of
using them, and actually having written an implementation of
printf, I still have to check with the manual for anything but
the simplest formatting.
Once you get the hang of them, it's
very easy to perform relatively complex formatting with a very small
amount of code which only takes a small amount of time to write.
And it's impossible to write any maintainable code, because the
low level formatting details creep down into the high level
output statements.
Also, you never need to worry if some formatting setting "leaks" or
not (ie. if the stream will "remember" that setting or forget about
it immediately after printing the value).
The C++-style printing functions are much more verbose, and a
complex C one-liner can easily become over a dozen of lines of C++
(or, alternatively, a dozen of << operator calls in a row) using
diverse function names from <iostreamand <iomanip>.
Not if you use it correctly. (Anything can be abused, of
course.) The difference is that in the C output, you have to
provide all of the information for physical formatting in the
single statement. In C++, you provide the information for the
physical formatting in the manipulator (which works more or less
like a style sheet in a word processor); the client code just
invokes the correct logical manipulator. And most of the time,
even that isn't necessary, because all of the logical
information for formatting is implicit in the type of the
expression. So you end up with:

std::cout << myVariable ;

instead of:

printf( "%-30s %5.2f %3d",
myVariable.getName(),
myVariable.getValue1(),
myVariable.getValue2() ) ;

(What was that about printf being compact?) And of course, the
C++ version continues to work correctly when value2 is changed
from int to long, or when an additional value is added, or when
it is suddenly decided that value one need three digits after
the decimal.
In some cases it also feels a bit inconsistent whether some
stream setting is remembered or forgotten between << operator
calls. Most are forgotten, but some are remembered, causing
potential "formatting leaks".
That's probably the one real pain of iostream formatting. All
of the formatting flags except width are "sticky". So you throw
in a quick additional output for debugging purposes:

std::cout << std::hex << value << std::endl ;

and all of the output which follows is in hex. (It's a
"feature" when outputting tabular data, of course: set the
precision once, before iterating over the table. But
generally...)

My own manipulators restore the original formatting flags in
their destructor, i.e. at the end of the full expression. And
of course, I've got an RAII class for restoring the original
format as well, which can be used in a function which modifies
formatting. But I agree that such things really shouldn't be
necessary.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jul 24 '07 #6
James Kanze schreef:
On Jul 23, 9:39 am, Jojo <no_m...@thanx.comwrote:
>I was wondering how I can perform formatted output with C++ strings. For
example, suppose I have in plain C:
> sprintf(C_string, "%5.2f %6d");
>How can I do such a thing with C++ strings?

To do exactly the above is a bit awkward, since you need several
manipulators. But normally, you only do something like the
above because C doesn't offer any alternative. What is the
first argument? What is the second? What semantic
characteristic does the first have which means that it should be
formatted using %5.2f, for example. In C++, you define the
formatting for such semantic characteristics, then write
something like:

... << ItsAToto << totosValue << ...

Something like ItsAToto is called a manipulator. Anytime you
write an application, you define the logical manipulators for
the various semantics that you want to support on output. That
way, if the request comes that all Toto now have to be output
with three digits after the decimal, you just change the
manipulator.

Note that most of the time, you're not outputting int's or
double's, but user defined types, which already have a specific
application dependant semantic. In such cases, the type of
"totosValue" says it all, and you don't need the manipulator.

(In text processing, this is known as logical mark-up. Roughly
speaking: C requires you to specify the physical mark-up,
locally, at each output site. C++ allows you to define a style
sheet.)
>Using a string stream and
the << operator does not give me the formatting control like sprintf.

It gives you a lot more.
>Or did I miss something.... :-|

If you're not familiar with maniipulators, or user defined
operator<<, you've missed practically all of iostream. (The
third important point is user defined streambufs.)
Well, maybe I can see that I didn't miss it because I haven't take a
close look at it yet... :-) Or is this too far from programmers logic?
Nevertheless, thanks for your explanation and I'll definitly take a deep
dive into iostream to become more familiar with it.

Jeroen
>
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jul 25 '07 #7

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

Similar topics

12
by: Craig Thomson | last post by:
Do people generally try and output nicely formatted html from their scripts? I have been trying to, with variable indenting for tables etc. It makes it easier to see the html and perhaps debug...
4
by: Joe Flynt | last post by:
I'm try to display the output of ipconfig.exe to the web browser using: Apache/2.0.48 (Win32) mod_python/3.1.2b Python/2.3.2 but when I view http://server/cgi-bin/test.py i get the following...
4
by: Joerg Lehmann | last post by:
I am using Python 2.2.3 (Fedora Core 1). The problem is, that strings containing umlauts do not work as I would expect. Here is my example: >>> a = 'äöü' >>> b = '123' >>> print "%-5s...
2
by: Mark | last post by:
How do I output formatted numerical data to an external (text) file. At a minimum I want to specify the number of decimal places to print. Ideally I'd like the type of control the fortran FORMAT...
6
by: Jason Heyes | last post by:
I am starting to worry about the performance of formatted read/write operations on data-redundant objects in my program.What can I do to improve this performance should it become an issue? ...
2
by: Steven T. Hatton | last post by:
I'm still not completely sure what's going on with C++ I/O regarding the extractors and inserters. The following document seems a bit inconsistent:...
3
by: Craig Petrie | last post by:
Hi, I have a large table in Word 2003 that has formatted text in the cells and wish to read and convert a cells formatted contents to html output via vb.net code. The formatting contains the...
6
by: bfowlkes | last post by:
Hello, I am trying to parse two pre-formatted text files and write them to a different files formatted in a different way. The story about this is I was hired along with about 20 other people...
6
by: Prime Mover | last post by:
In C, if I have three variables obtained in a loop like: for(i=0;i<N;i++) { x = ....{expression here}; y = ....{expression here}; z = ....{expression here}; }
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.