Re: arbitrary number of digits at integer representation
Carl Barron wrote:
In article <1149757047.131133.313940@y43g2000cwc.googlegroups.com>,
kanze <kanze@gabi-soft.fr> wrote:
std::string
cppFormat(
int value,
int width,
int prec )
{
std::ostringstream tmp ;
tmp << std::setfill( '0' ) << std::setw( prec ) << value ;
std::ostringstream result ;
result << std::setw( width ) << tmp.str() ;
return result.str() ;
}
Note too that it takes two separate ostringstream's to do this.
does it?? does not setting the fill and the width as writing to an
ostringstream give a string of the desired value?
It depends on the desired value:-). If the desired value is a string
of
at least width characters, with at least prec digits, then it only
gives
the desired value if width and prec are equal.
If you want to write it to an otherstream then this test code seems to
work.
#include <sstream>
#include <iostream>
#include <ostream>
#include <iomanip>
#include <string>
class write_value
{
int value;
int width;
public:
write_value(int a,int b):value(a),width(b){}
std::ostream & operator () (std::ostream &os)const
{
std::ostringstream str;
str << std::setfill('0') << std::setw(width) << value;
return os << str.str();
}
};
inline
std::ostream & operator << (std::ostream &os,const write_value &value)
{
return value(os);
}
int main()
{
std::cout << write_value(4,6) << '\n';
}
this just creates the string.
std::string create_string(int value,int width)
{
std::ostringstream str;
str << std::setfill('0') << std::setw(width) << value;
return str.str();
}
what am I missing???
Where do you specify the minimum number of digits? All I see is a
minimum width. To get both (separately), you would need to output
std::cout << std::setw( 8 ) << write_value( 4, 6 ) << std::endl ;
In sum, use a second stream. (My understanding was that the goal was
to
obtain a string which would be displayed in a GUI. Unless the GUI has
some sort of formatting commands to force padding to a minimum width,
you need two ostreams, one to pad with the '0's, and the second to
finish the padding with spaces.
--
James Kanze GABI Software
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
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]