473,835 Members | 1,971 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sprintf style printing in C++

I am not making much progress porting some old C code to C++ ...

I am porting the lines below, which prints an ISO8601 date string:

char buff[16] ;
memset(buff, '\0',16);
sprintf(buff,"% 02d:%02d:%02d", hours, minutes, seconds) ;

to :

std::ostringstr eam os ;
os << std::setprecisi on(2) << hours << ":" << std::setprecisi on(2) <<
minutes << std::setprecisi on(2) << seconds ;
The C++ code compiles ok, but I am getting the wrong formatting (i.e.
for old time C programmers) - its as if I'm using the format string
"%2d:%2d%2d "

Can anyone spot where I'm going wrong ?
Apr 23 '07 #1
5 4459
2b|!2b==? wrote:
I am not making much progress porting some old C code to C++ ...

I am porting the lines below, which prints an ISO8601 date string:

char buff[16] ;
memset(buff, '\0',16);
sprintf(buff,"% 02d:%02d:%02d", hours, minutes, seconds) ;

to :

std::ostringstr eam os ;
os << std::setprecisi on(2) << hours << ":" << std::setprecisi on(2) <<
minutes << std::setprecisi on(2) << seconds ;
The C++ code compiles ok, but I am getting the wrong formatting (i.e.
for old time C programmers) - its as if I'm using the format string
"%2d:%2d%2d "

Can anyone spot where I'm going wrong ?
You need to add setfill('0'), I believe.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 23 '07 #2

"2b|!2b==?" <ro**@your.box. comwrote in message
news:Dc******** *************** *******@bt.com. ..
>I am not making much progress porting some old C code to C++ ...

I am porting the lines below, which prints an ISO8601 date string:

char buff[16] ;
memset(buff, '\0',16);
sprintf(buff,"% 02d:%02d:%02d", hours, minutes, seconds) ;

to :

std::ostringstr eam os ;
os << std::setprecisi on(2) << hours << ":" << std::setprecisi on(2) <<
minutes << std::setprecisi on(2) << seconds ;
The C++ code compiles ok, but I am getting the wrong formatting (i.e. for
old time C programmers) - its as if I'm using the format string
"%2d:%2d%2d "

Can anyone spot where I'm going wrong ?
You should use width instead of precision, and use a '0' fill character (see
std::setw and std::setfill in <iomanip>)

- Sylvester Hesp
Apr 23 '07 #3
On Mon, 23 Apr 2007 15:51:44 +0100 in comp.lang.c++, "2b|!2b==?"
<ro**@your.box. comwrote,
> os << std::setprecisi on(2) << hours << ":" << std::setprecisi on(2) <<
minutes << std::setprecisi on(2) << seconds ;
You need setfill('0') and width(2).
setprecision is for floating point.

Apr 23 '07 #4
On Apr 23, 5:23 pm, "Sylvester Hesp" <s.h...@oisyn.n lwrote:
"2b|!2b==?" <r...@your.box. comwrote in message
news:Dc******** *************** *******@bt.com. ..
I am not making much progress porting some old C code to C++ ...
I am porting the lines below, which prints an ISO8601 date string:
char buff[16] ;
memset(buff, '\0',16);
sprintf(buff,"% 02d:%02d:%02d", hours, minutes, seconds) ;
to :
std::ostringstr eam os ;
os << std::setprecisi on(2) << hours << ":" << std::setprecisi on(2) <<
minutes << std::setprecisi on(2) << seconds ;
The C++ code compiles ok, but I am getting the wrong formatting (i.e. for
old time C programmers) - its as if I'm using the format string
"%2d:%2d%2d "
Can anyone spot where I'm going wrong ?
You should use width instead of precision, and use a '0' fill
character (see std::setw and std::setfill in <iomanip>)
Just for the record, in the more general case (outputting to a
file), you should save the previous fill character, and restore
it when you're through. (Obviously, it doesn't matter here,
since the stream is a local variable which will go immediately
out of scope when he's through.)

More generally, for time, I would not use ostringstream, but the
old C standby: strftime. It avoids most of the problems
inherent with sprintf, and it allows for localization when
appropriate.

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

Apr 24 '07 #5
James Kanze <ja*********@gm ail.comwrote:
>"2b|!2b==?" <r...@your.box. comwrote in message
news:Dc******* *************** ********@bt.com ...
I am porting the lines below, which prints an ISO8601 date string:
[snip]
More generally, for time, I would not use ostringstream, but the
old C standby: strftime. It avoids most of the problems
inherent with sprintf, and it allows for localization when
appropriate.
I would agree with James Kanze's advice to use strftime(). However, I
do not think localization is relevant in this particular instance since
the OP said he wanted to print an ISO8601 string, which AFAIU is
designed to eliminate localization issues :)

See:
http://www.cl.cam.ac.uk/~mgk25/iso-time.html

where he gives conversion specifiers for strftime() to output in
ISO8601 format.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Apr 26 '07 #6

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

Similar topics

6
2660
by: Venkat Venkataraju | last post by:
Hi All I'm having problems printing a string with a % char. Here is the code line = sprintf("<table width=100% id=%s>\n", $table_id); I'm getting an not enough parameter error. The % for the 100% is being mis interepreted as a format char. Though i worked around by coding it line = sprintf("<table width=100%s id=%s>\n", '%', $table_id);, i think there should be a way with which the % can be escaped PHP.
2
2533
by: Huey | last post by:
Hi All, I saved hashed values of hex into buf, then buf becomes unreadable by the means of calling puts(buf), printf("%s") and so on. Then, I need to convert the hex in buf into a char buffer cbuf, by calling sprintf(). I did: sprintf(cbuf, "%x", buf); No error! Just no working. Well, I used sprintf() a lot in format "%s"
32
440
by: Michele | last post by:
I have a code line like this: sprintf(buf, "%20g",*(liftPtr++)) what does it mean? And what does the function sprintf do? Thanks michele
6
2504
by: jt | last post by:
I need to produce 1 character array from 3 others. I tried sprintf and it terminates on the first 0, null, 0x00 it sees in tmp data. All 3 args print out nice by themselves. By trying to make the character array(alerts.msg) with sprintf doesn't work for the obvious reasons in my first sentence with tmp having those control characters. Is there another way to do this? To accomplish the same thing that sprintf does but able to do having...
12
15227
by: babak | last post by:
Hi everyone I want to format a string (using sprintf) and put it in a messagebox but however I try to do it, it doesn't seem to work. Here is an example sample of what i try to do: char msg; string my_name = "John"; sprintf (msg, "My name is: %s ", my_name); MessageBox(NULL, msg, NULL, MB_OK);
10
4201
by: Saurabh | last post by:
Hi all, I am working on RedHat Linux GCC 3.0. I am trying to convert a long to string through sprintf. but i m getting segmantation fault. I tried snprintf also but no avail.here is the piece of code.. ---------------------------- long myLong=200000; char myStr;
6
11644
by: Henryk | last post by:
I did a lot of delphi GUI programming recently. In my experience most of the time you just want to throw a standard exception with a descriptive message. Then all calling functions can handle this exception as they like and finally show a message to the user or not. Only in a few occasions I need some special exception types to behave differently depending on the error. So what you basically do is
15
3536
by: krister | last post by:
Hello, I'm working in a quite large system that has some limitations. One of those is that I can't use printf() to get an output on a screen. I'm forced to use a special function, let's call it PrintOnConsole(), to get the output on a console. The problem with PrintOnConsole() is that it only takes strings as input arguments. On the other hand, I'm free to use sprintf(), so I can convert everything I want to print into a string and then...
2
1645
by: Lars Eighner | last post by:
I notice that many examples in the manual use sprintf in constructing database query strings. Is this just style, or are there some serious advantages to sprintf over concatenating the string, assuming in both cases that the variable parts of the string are properly sanitized? -- Lars Eighner <http://larseighner.com/ <http://myspace.com/larseighner> Countdown: 566 days to go. Friends of Lizbeth: help replace failed a/c at...
0
9810
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
9653
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
10815
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...
1
7768
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6968
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5639
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...
0
5805
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4434
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
3
3092
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.