home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / c / 12940 < prev    next >
Encoding:
Text File  |  1992-08-29  |  1.7 KB  |  70 lines

  1. Path: sparky!uunet!mcsun!uknet!glasgow!unix.brighton.ac.uk!amn
  2. From: amn@unix.brighton.ac.uk (Anthony Naggs)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: printf question
  5. Message-ID: <1992Aug28.235520.19363@unix.brighton.ac.uk>
  6. Date: 28 Aug 92 23:55:20 GMT
  7. References: <1992Aug27.143434.26965@dartvax.dartmouth.edu>
  8. Reply-To: amn@vms.brighton.ac.uk
  9. Organization: University of Brighton, England
  10. Lines: 58
  11.  
  12. Edward H. Truex, <eht@coos.dartmouth.edu> wants a simpler way of doing:
  13. > #define ADDR_BITS 16
  14. >
  15. > ... blah blah ...
  16. >
  17. > main( int argc, char *argv[] ){
  18. >
  19. > ... blah blah ...
  20. >
  21. > sprintf( format_string, "%%0%dx\n", ADDR_BITS/4 );
  22. > printf( format_string, address );
  23. >
  24. > ... blah blah ...
  25. >
  26.  
  27. > exit(0);
  28. > }
  29.  
  30. A couple of answers come to mind, answer 1 removes the sprintf:
  31. 1> #define ADDR_BITS 16
  32. 1>
  33. 1> ... blah blah ...
  34. 1>
  35. 1> main( int argc, char *argv[] ){
  36. 1>
  37. 1> ... blah blah ...
  38. 1>
  39. 1> /* the '*' takes an int from the parameter list for the field width */
  40. 1> printf( "%*x\n", ADDR_BITS/4, address );
  41. 1>
  42. 1> ... blah blah ...
  43. 1>
  44. 1> exit(0);
  45. 1> }
  46.  
  47. Answer 2, as requested, incorporates the defined value in the format string:
  48. 2> #define DISP_DIGITS "4"                  /* Displayed digits as a string */
  49. 2>
  50. 2> ... blah blah ...
  51. 2>
  52. 2> main( int argc, char *argv[] ){
  53. 2>
  54. 2> ... blah blah ...
  55. 2>
  56. 2> /* Uses ANSI C concatenation of string literals */
  57. 2> printf( "%" DISP_DIGITS "x\n", address );
  58. 2>
  59. 2> ... blah blah ...
  60. 2>
  61. 2> exit(0);
  62. 2> }
  63.  
  64. Regards, Anthony Naggs
  65.  
  66. Software/Electronics Engineer                   P O Box 1080, Peacehaven
  67.                                                 East Sussex  BN10 8PZ
  68. Phone: +44 273 589701                           Great Britain
  69. Email, (c/o Univ of Brighton): amn@vms.brighton.ac.uk
  70.