473,387 Members | 1,834 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,387 software developers and data experts.

ios output width

Hi,

I'd like to use copy() to send the content of an integer container to
cout. How can I make sure that /all/ of them are printed with width 2?

#include <iostream>
#include <iterator>

int v[]={42,3,42};

using namespace std;

int main(){
cout.width(2);
copy(v,v+3,ostream_iterator<int>(cout," "));
cout<<endl;
return 0;
}

gives

42 3 42

I'd like it to be

42 3 42

instead. I read in Stroustrup that width() only applies to the next
output. I thought using format flags with setf would be the way to do it
like when I want to output the integers in say octal. But there are no
format "flags" for width. What can I do?

Ralf
Dec 6 '07 #1
6 2101
On Thu, 06 Dec 2007 17:27:13 +0100 in comp.lang.c++, Ralf Goertz
<r_******@expires-2006-11-30.arcornews.dewrote,
>I'd like to use copy() to send the content of an integer container to
cout. How can I make sure that /all/ of them are printed with width 2?
You realize that by requiring std::copy you are doing it the hard
way? Homework?

You could define an adapter class that is implicitly constructed
from the int, and use output_iterator<adapterto call your code to
do the formatting.
Dec 6 '07 #2
David Harmon wrote:
Ralf Goertz wrote
>>I'd like to use copy() to send the content of an integer container to
cout. How can I make sure that /all/ of them are printed with width 2?

You realize that by requiring std::copy you are doing it the hard
way? Homework?
No, it's not homework. Reading this newsgroup I got the impression that
using std::copy is the preferred way to output containers. So yes I
could have used a loop to do it. That is not the point. I wonder why one
can *permanently* switch an output stream to another base but not to a
width other than 0. I thought that I had missed something, that's why I
asked.
You could define an adapter class that is implicitly constructed
from the int, and use output_iterator<adapterto call your code to
do the formatting.
Okay, thanks. But that surely is "doing it the hard way".

Ralf
Dec 7 '07 #3
On Dec 6, 5:27 pm, Ralf Goertz
<r_goe...@expires-2006-11-30.arcornews.dewrote:
I'd like to use copy() to send the content of an integer
container to cout. How can I make sure that /all/ of them are
printed with width 2?
You can't. An ostream will never output a field with less width
than is necessary to display it correctly, so any value outside
the range of [-9...99] will display wider.
#include <iostream>
#include <iterator>
int v[]={42,3,42};
using namespace std;
int main(){
cout.width(2);
copy(v,v+3,ostream_iterator<int>(cout," "));
ostream_iterator is pretty worthless as classes go. You'll have
to write your own if you want anything but the simplest
formatting. (The implementation shouldn't be that difficult.
Defining the interface so that you don't have to specify more
than you need is far from trivial, however.)
cout<<endl;
return 0;
}
gives
42 3 42
I'd like it to be
42 3 42
instead. I read in Stroustrup that width() only applies to the
next output.
That's the convention.

You could write a class along the lines of:

class FixedWidthInt
{
public:
FixedWidthInt( int i ) : i( i ) {}
friend std::ostream& operator<<(
std::ostream& dest,
FixedWidthInt const&obj )
{
int w = dest.width() ;
dest << obj.i ;
dest.width( w ) ;
return *dest ;
}
private:
int i ;
} ;

and invoke:

std::cout.width( 2 ) ;
copy( v.begin(), v.end(),
std::ostream_iterator< FixedWidthInt >( std::cout ) ) ;

I don't like it, though; it more or less changes the expected
behavior of the ostream. Alternatively, if the width is always
constant, you could use a template:

template< int w >
class FixedWidthInt
{
public:
FixedWidthInt( int i ) : i( i ) {}
friend std::ostream& operator<<(
std::ostream& dest,
FixedWidthInt const&obj )
{
dest << std::setw( w ) << obj.i ;
return *dest ;
}
private:
int i ;
} ;

// ...

copy( v.begin(), v.end(),
std::ostream_iterator< FixedWidthInt< 2 ( std::cout ) ) ;

This seems more acceptable to me, since you aren't counting on
the width not changing. (I.e. this FixedWidthInt doesn't cause
the width not to be reset, against expectations of a <<
operator. The preceding one does.)

Finally, you could arrange that FixedWidthInt get the width, not
from a template argument (which must be a compile time
constant), but from a special format field, set by
maniipulators. Something like the following:

class FixedWidthBase
{
public:
static long width( std::ios& stream )
{
return stream.iword( index() ) ;
}

static long width( std::ios& stream, long newWidth )
{
std::swap( stream.iword( index() ), newWidth ) ;
return newWidth ;
}

private:
static int index()
{
if ( ourWidth < 0 ) {
ourWidth = std::ios::xalloc() ;
}
return ourWidth ;
}
static int ourWidth ;
} ;

int FixedWidthBase::ourWidth = -1 ;

template< typename T >
class FixedWidth : private FixedWidthBase
{
public:
FixedWidth( T const& value )
: myValue( value )
{
}

friend std::ostream&
operator<<(
std::ostream& dest,
FixedWidth const& obj )
{
dest << std::setw( width( dest ) ) << obj.myValue ;
return dest ;
}

private:
T myValue ;
} ;

int
fixedwidth(
std::ios& stream,
int newWidth )
{
return FixedWidthBase::width( stream, newWidth ) ;
}

// ...

fixedwidth( std::cout, 3 ) ;
std::copy(
v.begin(), v.end(),
std::ostream_iterator< FixedWidth< int ( std::cout,
"\n" ) ) ;
I thought using format flags with setf would be the way to do
it like when I want to output the integers in say octal. But
there are no format "flags" for width. What can I do?
See above. The real solution is to design and implement an
ostream_iterator that is useful, but that's decidedly
non-trivial. Failing that, I suspect that the template version
of FixedWidth that I propose above might be a useful snippet.

Another important thing to remember: there is no requirement
that the type of the ostream_iterator be the same as the type
you are writing. All you need is that the type you are writing
be convertible to it. You can do an awful lot with user defined
classes along the lines of those above. (It's far from perfect,
but it solves a lot of problems with ostream_iterator.)

--
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
Dec 7 '07 #4
On Dec 7, 8:42 am, Ralf Goertz
<r_goe...@expires-2006-11-30.arcornews.dewrote:
David Harmon wrote:
Ralf Goertz wrote
>I'd like to use copy() to send the content of an integer container to
cout. How can I make sure that /all/ of them are printed with width 2?
You realize that by requiring std::copy you are doing it the hard
way? Homework?
No, it's not homework. Reading this newsgroup I got the
impression that using std::copy is the preferred way to output
containers. So yes I could have used a loop to do it. That is
not the point. I wonder why one can *permanently* switch an
output stream to another base but not to a width other than 0.
I thought that I had missed something, that's why I asked.
Alternatively, one might ask why one can set the length for a
single output, but one can't set the base for a single output.

I'm not really sure that there's much logic behind which is
which: width is volatile, and all of the others permanent. But
it's easy to get the other effect when you need it: all of my
manipulators restore the original state in their destructor, for
example (so any changes loose effect at the end of the full
expression), and it's pretty easy to add state, and manipulators
which manipulate it, as I did in my answer to your posting.
You could define an adapter class that is implicitly
constructed from the int, and use output_iterator<adapter>
to call your code to do the formatting.
Okay, thanks. But that surely is "doing it the hard way".
Not if it solves a general problem. Creating a class which
outputs an int, always with width 2, is doing it the hard way.
Creating a template class which outputs its type with the width
it reads from an additional state variable may require a little
more code to begin with (it took me about 15 minutes to write
and test -- where as writing the loop would probably take less
than a minute), but it could easily save work in the long run,
if the problem is frequent.

--
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
Dec 7 '07 #5
James Kanze wrote:
On Dec 6, 5:27 pm, Ralf Goertz
<r_goe...@expires-2006-11-30.arcornews.dewrote:
>I'd like to use copy() to send the content of an integer
container to cout. How can I make sure that /all/ of them are
printed with width 2?

You could write a class along the lines of:

class FixedWidthInt
{
public:
FixedWidthInt( int i ) : i( i ) {}
friend std::ostream& operator<<(
std::ostream& dest,
FixedWidthInt const&obj )
{
int w = dest.width() ;
dest << obj.i ;
dest.width( w ) ;
return *dest ;
}
private:
int i ;
} ;

and invoke:

std::cout.width( 2 ) ;
copy( v.begin(), v.end(),
std::ostream_iterator< FixedWidthInt >( std::cout ) ) ;
That - to my surprise - didn't work. That is (after having changed
"return *dest" to "return dest") it compiled but only wrote the first
int with width 2 like my own attempt.

gcc-Version 4.2.1 (SUSE Linux)

I don't like it, though; it more or less changes the expected
behavior of the ostream. Alternatively, if the width is always
constant, you could use a template:

template< int w >
class FixedWidthInt
{
public:
FixedWidthInt( int i ) : i( i ) {}
friend std::ostream& operator<<(
std::ostream& dest,
FixedWidthInt const&obj )
{
dest << std::setw( w ) << obj.i ;
return *dest ;
}
private:
int i ;
} ;
I also like this better and it worked (again after replacing "*dest" by
"dest"). Something like that was what I expected to find in the standard.
This seems more acceptable to me, since you aren't counting on
the width not changing. (I.e. this FixedWidthInt doesn't cause
the width not to be reset, against expectations of a <<
operator. The preceding one does.)

Finally, you could arrange that FixedWidthInt get the width, not
from a template argument (which must be a compile time
constant), but from a special format field, set by
maniipulators. Something like the following:
I think I would go with the template as I usually know at compile time
what width I need.

>I thought using format flags with setf would be the way to do
it like when I want to output the integers in say octal. But
there are no format "flags" for width. What can I do?

See above. The real solution is to design and implement an
ostream_iterator that is useful, but that's decidedly
non-trivial. Failing that, I suspect that the template version
of FixedWidth that I propose above might be a useful snippet.
Yes it is. Thanks a lot.

Ralf
Dec 7 '07 #6
On Dec 7, 6:18 pm, Ralf Goertz
<r_goe...@expires-2006-11-30.arcornews.dewrote:
James Kanze wrote:
On Dec 6, 5:27 pm, Ralf Goertz
<r_goe...@expires-2006-11-30.arcornews.dewrote:
I'd like to use copy() to send the content of an integer
container to cout. How can I make sure that /all/ of them are
printed with width 2?
You could write a class along the lines of:
class FixedWidthInt
{
public:
FixedWidthInt( int i ) : i( i ) {}
friend std::ostream& operator<<(
std::ostream& dest,
FixedWidthInt const&obj )
{
int w = dest.width() ;
dest << obj.i ;
dest.width( w ) ;
return *dest ;
}
private:
int i ;
} ;
and invoke:
std::cout.width( 2 ) ;
copy( v.begin(), v.end(),
std::ostream_iterator< FixedWidthInt >( std::cout ) ) ;
That - to my surprise - didn't work. That is (after having changed
"return *dest" to "return dest") it compiled but only wrote the first
int with width 2 like my own attempt.
I did say "along the lines of". That's sort of a blatant
admission that I just typed it in directly, without having tried
it. The "return *dest" is proof of it as well.

In fact, of course, the problem is that every output resets the
width. So if there's any output between two FixedWidthInt, the
width will get reset as well. Which makes it very, very fragile
at best.
gcc-Version 4.2.1 (SUSE Linux)
I don't like it, though; it more or less changes the expected
behavior of the ostream. Alternatively, if the width is always
constant, you could use a template:
template< int w >
class FixedWidthInt
{
public:
FixedWidthInt( int i ) : i( i ) {}
friend std::ostream& operator<<(
std::ostream& dest,
FixedWidthInt const&obj )
{
dest << std::setw( w ) << obj.i ;
return *dest ;
}
private:
int i ;
} ;
I also like this better and it worked (again after replacing
"*dest" by "dest"). Something like that was what I expected to
find in the standard.
Do you mean, used by ostream_iterator, or as an additional
formatting parameter. I've occasionally felt that there should
be two copies of all of the formatting parameters: one volatile,
and one sticky. The convention would be that << sets all of the
volatile ones to the sticky values when it finishes. But of
course, then, you'd need two sets of manipulators, etc. It's
probably more complexity than it is worth.
This seems more acceptable to me, since you aren't counting
on the width not changing. (I.e. this FixedWidthInt doesn't
cause the width not to be reset, against expectations of a
<< operator. The preceding one does.)
Finally, you could arrange that FixedWidthInt get the width,
not from a template argument (which must be a compile time
constant), but from a special format field, set by
maniipulators. Something like the following:
I think I would go with the template as I usually know at
compile time what width I need.
I think that's usually the case. And the template form is
considerably simpler (and doesn't have the threading issues of
the more general form).

--
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
Dec 9 '07 #7

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

Similar topics

1
by: thomas | last post by:
I'm building a guitar website which uses XML and XSLT. http://www.madtim67.com/guitar/index.html You can search either by artist or song. I used the <xsl:if test="contains(artist ,$text1)"> line...
2
by: Thomas Hermann | last post by:
A newbie question: With the config mentioned in the topic, all on localhost, Win xpsp2, i created a caledar-table. The output should be a daily calendar for half a year with about 15 cols. ...
3
by: bloc | last post by:
I am programming an interactive CV using xml, xslt and java script. The page consists of a header which contains links to various 'sections' on the xml cv, a left and right menu, and a central...
3
by: rsteph | last post by:
I have a script that shows the time and date. It's been working on my site for quite a while now. Suddenly it stops showing up, after getting my drop down menu to work. If I put text between the...
2
by: Bill Nguyen | last post by:
Is there a way to send output from a .NET app to a selected monitor screen in a 3-monitor client desktop? Currently, my app sends output to 3 windows then I have to move/drag each of them to the...
6
by: cfish | last post by:
I'm trying to script my contact page and I have everything the way I want it however I cannot get my script to output Address, City, State, Zip & Phone Number when I get a email. It will output...
19
by: Chad | last post by:
Okay, let's say I have an exotic os that limits how much goes to stdout. When I go like.. #include <stdio.h> int main(void) { int i=0; for(i=0; i< 10; i++) { printf("a \n");
0
by: solostation | last post by:
Hi I need to modify the output size upon click on 'more photos" so that I can add some pictures in the out put box ... The relevent html code I can find (copied from the display html) is as...
3
by: realmerl | last post by:
Hi All. I'm trying to transform a html document into plain text via xslt. Simple you say! (i hope) I have got it working, by using the magnificent <xsl:value-of select="."/>. This returns the...
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: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...
0
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...

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.