home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!uknet!glasgow!unix.brighton.ac.uk!amn
- From: amn@unix.brighton.ac.uk (Anthony Naggs)
- Newsgroups: comp.lang.c
- Subject: Re: printf question
- Message-ID: <1992Aug28.235520.19363@unix.brighton.ac.uk>
- Date: 28 Aug 92 23:55:20 GMT
- References: <1992Aug27.143434.26965@dartvax.dartmouth.edu>
- Reply-To: amn@vms.brighton.ac.uk
- Organization: University of Brighton, England
- Lines: 58
-
- Edward H. Truex, <eht@coos.dartmouth.edu> wants a simpler way of doing:
- > #define ADDR_BITS 16
- >
- > ... blah blah ...
- >
- > main( int argc, char *argv[] ){
- >
- > ... blah blah ...
- >
- > sprintf( format_string, "%%0%dx\n", ADDR_BITS/4 );
- > printf( format_string, address );
- >
- > ... blah blah ...
- >
-
- > exit(0);
- > }
-
- A couple of answers come to mind, answer 1 removes the sprintf:
- 1> #define ADDR_BITS 16
- 1>
- 1> ... blah blah ...
- 1>
- 1> main( int argc, char *argv[] ){
- 1>
- 1> ... blah blah ...
- 1>
- 1> /* the '*' takes an int from the parameter list for the field width */
- 1> printf( "%*x\n", ADDR_BITS/4, address );
- 1>
- 1> ... blah blah ...
- 1>
- 1> exit(0);
- 1> }
-
- Answer 2, as requested, incorporates the defined value in the format string:
- 2> #define DISP_DIGITS "4" /* Displayed digits as a string */
- 2>
- 2> ... blah blah ...
- 2>
- 2> main( int argc, char *argv[] ){
- 2>
- 2> ... blah blah ...
- 2>
- 2> /* Uses ANSI C concatenation of string literals */
- 2> printf( "%" DISP_DIGITS "x\n", address );
- 2>
- 2> ... blah blah ...
- 2>
- 2> exit(0);
- 2> }
-
- Regards, Anthony Naggs
-
- Software/Electronics Engineer P O Box 1080, Peacehaven
- East Sussex BN10 8PZ
- Phone: +44 273 589701 Great Britain
- Email, (c/o Univ of Brighton): amn@vms.brighton.ac.uk
-