printf padding with alternate character?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • pb

    printf padding with alternate character?

    Im wanted to pad out blank spaces with a specific character instead of
    spaces or zeros, does C support that?

    printf("$%*d", '*', 5); // Not sure what the format string is supposed to
    look like to do this

    example output i would want is this:
    $********5


  • Ben Pfaff

    #2
    Re: printf padding with alternate character?

    "pb" <glace99@yahoo. com> writes:
    [color=blue]
    > Im wanted to pad out blank spaces with a specific character instead of
    > spaces or zeros, does C support that?[/color]

    No. You will have to write your own code to do it.
    --
    Ben Pfaff
    email: blp@cs.stanford .edu
    web: http://benpfaff.org

    Comment

    • Chris Torek

      #3
      Re: printf padding with alternate character?

      In article <1103068973.180 47@sj-nntpcache-3> pb <glace99@yahoo. com> wrote:[color=blue]
      >Im wanted to pad out blank spaces with a specific character instead of
      >spaces or zeros, does C support that?[/color]

      No.
      [color=blue]
      >printf("$%*d ", '*', 5); // Not sure what the format string is supposed to
      >look like to do this[/color]

      (Note that //-comments wrap around, so that if this had been intended
      to be a code example, it would not have worked so well.

      The "*" in "%*d" is a field-width specifier that reads an "int"
      argument from the argument list, so:

      printf("%*d", 2, 5);

      prints the value "5" in a ten-character field. The field is blank
      or zero padded depending on the pad option selected: blank by
      default, zero if you use a 0 modifier.)
      [color=blue]
      >example output i would want is this:
      >$********5[/color]

      There is no standard way to do this. It is easy to build your own
      though: just sprintf() the numeric value, and then work with the
      string. In this case, to get an integer printed into a ten digit
      field and replace leading blanks or zeros with spaces, just do
      something like:

      char buf[SOME_SIZE]; /* must be at least 11 chars */
      int val;
      ...
      sprintf(buf, "%010d", val); /* produces, e.g., 0000000005 */
      subst(buf, '0', '*');

      where the subst() function reads:

      /*
      * Do substitutions on leading characters in the given string:
      * Replace all occurrences of "from" with "to". (We assume
      * from != '\0'.)
      */
      void subst(char *s, char from, char to) {
      while (*s == from)
      *s++ = to;
      }

      Note that if you print with leading blanks, you will need to subst()
      from ' ' instead of '0'. (This trick works either way.)
      --
      In-Real-Life: Chris Torek, Wind River Systems
      Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
      email: forget about it http://web.torek.net/torek/index.html
      Reading email is like searching for food in the garbage, thanks to spammers.

      Comment

      • Peter Nilsson

        #4
        Re: printf padding with alternate character?

        pb wrote:[color=blue]
        > Im wanted to pad out blank spaces with a specific character instead[/color]
        of[color=blue]
        > spaces or zeros, does C support that?[/color]

        Yes, but not directly through a standard function.
        [color=blue]
        > printf("$%*d", '*', 5); // Not sure what the format string is[/color]
        supposed to[color=blue]
        > look like to do this
        >
        > example output i would want is this:
        > $********5[/color]

        #include <stdio.h>
        #include <string.h>

        #define HASH "*********"

        int main(void)
        {
        int amount = 520;
        char number[100];
        sprintf(number, "%d.%02d", amount / 100, amount % 100);
        printf( "$%.*s%s\n" ,
        (int) (sizeof HASH - 1 - strlen(number)) ,
        HASH,
        number );
        return 0;
        }

        BTW, $ is not a member of the basic character set.

        --
        Peter

        Comment

        • Mike Wahler

          #5
          Re: printf padding with alternate character?


          "pb" <glace99@yahoo. com> wrote in message
          news:1103068973 .18047@sj-nntpcache-3...[color=blue]
          > Im wanted to pad out blank spaces with a specific character instead of
          > spaces or zeros, does C support that?
          >
          > printf("$%*d", '*', 5); // Not sure what the format string is supposed to
          > look like to do this
          >
          > example output i would want is this:
          > $********5[/color]

          You've got many good answers already. Here's another
          alternative:

          #include <iostream>
          #include <string>
          #include <stdio.h>

          unsigned int digits(int value, unsigned int radix)
          {
          unsigned int result = 0;

          if(value < 0)
          value *= -1;

          result = !value;

          while(value)
          {
          ++result;
          value /= radix;
          }

          return result;
          }

          int main()
          {
          int value = 42;
          int wid = 5;
          char prefix = '$';
          int leading = 0;
          char pad = '*';
          int i = 0;
          unsigned int d = digits(value, 10) + (value < 0);

          if(d > wid)
          wid = d;

          leading = wid - d ;

          putchar(prefix) ;

          for(i = 0; i < leading; ++i)
          putchar(pad);

          printf("%d\n", value);
          return 0;
          }

          -Mike


          Comment

          • Martin Ambuhl

            #6
            Re: printf padding with alternate character?

            Mike Wahler wrote:
            [color=blue]
            > You've got many good answers already. Here's another
            > alternative:
            >
            > #include <iostream>
            > #include <string>
            > #include <stdio.h>[/color]

            Did you forget this was comp.lang.c? It's a good thing, since you might
            have gotten flamed in comp.lang.c++ for <stdio.h> instead of <cstdio>,
            or, in their anti-C exuberance, for using either.

            Comment

            • Mike Wahler

              #7
              Re: printf padding with alternate character?


              "Martin Ambuhl" <mambuhl@earthl ink.net> wrote in message
              news:329tqnF3l8 pb9U1@individua l.net...[color=blue]
              > Mike Wahler wrote:
              >[color=green]
              > > You've got many good answers already. Here's another
              > > alternative:
              > >
              > > #include <iostream>
              > > #include <string>
              > > #include <stdio.h>[/color]
              >
              > Did you forget this was comp.lang.c?[/color]

              Actually, no. Those C++ headers are 'residue' from
              a 'scratch' file I forgot to delete. (I suppose they
              must have been scrolled off the screen.)
              [color=blue]
              > It's a good thing, since you might
              > have gotten flamed in comp.lang.c++ for <stdio.h> instead of <cstdio>,[/color]

              Any flames about that would be unjustified. <stdio.h>
              is as valid a standard header in C++ as in C. But yes,
              I know, some folks don't know any better.
              [color=blue]
              > or, in their anti-C exuberance, for using either.[/color]

              Let's not go there. :-)

              But thanks for pointing out my error.
              I'll try to pay better attention in the future.

              -Mike


              Comment

              • Lawrence Kirby

                #8
                Re: printf padding with alternate character?

                On Wed, 15 Dec 2004 00:37:38 +0000, Chris Torek wrote:

                ....
                [color=blue]
                > printf("%*d", 2, 5);
                >
                > prints the value "5" in a ten-character field.[/color]

                Looks like a 2 character field to me. :-)
                [color=blue]
                > The field is blank
                > or zero padded depending on the pad option selected: blank by
                > default, zero if you use a 0 modifier.)
                >[color=green]
                >>example output i would want is this:
                >>$********5[/color]
                >
                > There is no standard way to do this. It is easy to build your own
                > though: just sprintf() the numeric value, and then work with the
                > string. In this case, to get an integer printed into a ten digit
                > field and replace leading blanks or zeros with spaces, just do
                > something like:
                >
                > char buf[SOME_SIZE]; /* must be at least 11 chars */
                > int val;
                > ...
                > sprintf(buf, "%010d", val); /* produces, e.g., 0000000005 */
                > subst(buf, '0', '*');
                >
                > where the subst() function reads:
                >
                > /*
                > * Do substitutions on leading characters in the given string:
                > * Replace all occurrences of "from" with "to". (We assume
                > * from != '\0'.)
                > */
                > void subst(char *s, char from, char to) {
                > while (*s == from)
                > *s++ = to;
                > }
                >
                > Note that if you print with leading blanks, you will need to subst()
                > from ' ' instead of '0'. (This trick works either way.)[/color]

                That depends on whether you want 0 to be output as ********** or
                *********0

                Lawrence

                Comment

                • Zoran Cutura

                  #9
                  Re: printf padding with alternate character?

                  Chris Torek <nospam@torek.n et> wrote:[color=blue]
                  > In article <1103068973.180 47@sj-nntpcache-3> pb <glace99@yahoo. com> wrote:[/color]
                  ....[color=blue]
                  > printf("%*d", 2, 5);[/color]
                  ^^^
                  10???[color=blue]
                  >
                  > prints the value "5" in a ten-character field. The field is blank[/color]
                  ^^^
                  two???
                  --
                  Z (zoran.cutura@w eb.de)
                  "LISP is worth learning for the profound enlightenment experience
                  you will have when you finally get it; that experience will make you
                  a better programmer for the rest of your days." -- Eric S. Raymond

                  Comment

                  • Chris Torek

                    #10
                    Re: printf padding with alternate character?

                    >On Wed, 15 Dec 2004 00:37:38 +0000, Chris Torek wrote:[color=blue][color=green]
                    >> printf("%*d", 2, 5);
                    >> prints the value "5" in a ten-character field.[/color][/color]

                    In article <pan.2004.12.15 .10.23.16.95300 0@netactive.co. uk>
                    Lawrence Kirby <lknews@netacti ve.co.uk> wrote:[color=blue]
                    >Looks like a 2 character field to me. :-)[/color]

                    Oops. Hasty posting....
                    [color=blue][color=green]
                    >> Note that if you print with leading blanks, you will need to subst()
                    >> from ' ' instead of '0'. (This trick works either way.)[/color]
                    >
                    >That depends on whether you want 0 to be output as ********** or
                    >*********0[/color]

                    Right, something else I managed to forget to bring up. And if this
                    is intended for printing money-amounts, one may have to fiddle with
                    negative numbers as more special cases.
                    --
                    In-Real-Life: Chris Torek, Wind River Systems
                    Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
                    email: forget about it http://web.torek.net/torek/index.html
                    Reading email is like searching for food in the garbage, thanks to spammers.

                    Comment

                    • Mike Wahler

                      #11
                      Re: printf padding with alternate character?

                      "Chris Torek" <nospam@torek.n et> wrote in message
                      news:cpq1g502ge @news1.newsguy. com...[color=blue][color=green]
                      > >On Wed, 15 Dec 2004 00:37:38 +0000, Chris Torek wrote:[color=darkred]
                      > >> printf("%*d", 2, 5);
                      > >> prints the value "5" in a ten-character field.[/color][/color]
                      >
                      > In article <pan.2004.12.15 .10.23.16.95300 0@netactive.co. uk>
                      > Lawrence Kirby <lknews@netacti ve.co.uk> wrote:[color=green]
                      > >Looks like a 2 character field to me. :-)[/color]
                      >
                      > Oops. Hasty posting....[/color]

                      I noticed it too, but realized it was merely a typo.
                      I didn't want to 'pick on' someone whose contributions
                      here I so highly value. :-)
                      [color=blue][color=green][color=darkred]
                      > >> Note that if you print with leading blanks, you will need to subst()
                      > >> from ' ' instead of '0'. (This trick works either way.)[/color]
                      > >
                      > >That depends on whether you want 0 to be output as ********** or
                      > >*********0[/color]
                      >
                      > Right, something else I managed to forget to bring up. And if this
                      > is intended for printing money-amounts, one may have to fiddle with
                      > negative numbers as more special cases.[/color]

                      While I did not test exhaustively, the example I posted allows
                      for the '-' character for negative values.

                      -Mike


                      Comment

                      • Chris Torek

                        #12
                        Re: printf padding with alternate character?

                        >"Chris Torek" <nospam@torek.n et> wrote in message[color=blue]
                        >news:cpq1g502g e@news1.newsguy .com...[color=green]
                        >> ... And if this
                        >> is intended for printing money-amounts, one may have to fiddle with
                        >> negative numbers as more special cases.[/color][/color]

                        In article <zk0wd.283$9j5. 18@newsread3.ne ws.pas.earthlin k.net>
                        Mike Wahler <mkwahler@mkwah ler.net> wrote:[color=blue]
                        >While I did not test exhaustively, the example I posted allows
                        >for the '-' character for negative values.[/color]

                        Well, yes; but I was referring to accountants' desire to print
                        negative numbers in parentheses, or with the minus sign at the
                        end, or with a "CR" (credit) or "DB" (debit) suffix, e.g.:

                        Your Bill

                        item 1 $***123.45
                        item 2 $****27.72 CR
                        total $****95.73

                        (I always thought these were obnoxious, myself. But my early
                        training was all mathematics rather than accounting. :-) )
                        --
                        In-Real-Life: Chris Torek, Wind River Systems
                        Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
                        email: forget about it http://web.torek.net/torek/index.html
                        Reading email is like searching for food in the garbage, thanks to spammers.

                        Comment

                        • Mike Wahler

                          #13
                          Re: printf padding with alternate character?


                          "Chris Torek" <nospam@torek.n et> wrote in message
                          news:cpq4r601r6 7@news4.newsguy .com...[color=blue][color=green]
                          > >"Chris Torek" <nospam@torek.n et> wrote in message
                          > >news:cpq1g502g e@news1.newsguy .com...[color=darkred]
                          > >> ... And if this
                          > >> is intended for printing money-amounts, one may have to fiddle with
                          > >> negative numbers as more special cases.[/color][/color]
                          >
                          > In article <zk0wd.283$9j5. 18@newsread3.ne ws.pas.earthlin k.net>
                          > Mike Wahler <mkwahler@mkwah ler.net> wrote:[color=green]
                          > >While I did not test exhaustively, the example I posted allows
                          > >for the '-' character for negative values.[/color]
                          >
                          > Well, yes; but I was referring to accountants' desire to print
                          > negative numbers in parentheses, or with the minus sign at the
                          > end, or with a "CR" (credit) or "DB" (debit) suffix, e.g.:
                          >
                          > Your Bill
                          >
                          > item 1 $***123.45
                          > item 2 $****27.72 CR
                          > total $****95.73[/color]

                          Oh, OK.
                          [color=blue]
                          >
                          > (I always thought these were obnoxious, myself. But my early
                          > training was all mathematics rather than accounting. :-) )[/color]

                          Well, I'm in the opposite 'camp'. All my early programming
                          learning was in the context of business applications (my first
                          HLL was COBOL :-) ), and yes, I had to deal with the forms
                          (value), valueCR, and value- as well. Since OP didn't give
                          context, I 'defaulted' to the 'simpler' -value. I suppose
                          the leading asterisks should have been a clue, though. :-)

                          Aside: One of the accounting oriented things I've done which
                          I found fun was converting a number to English (e.g. 3125 to
                          "Three thousand, one hundred twenty-five") for printing bank
                          drafts. :-)

                          I do wish I'd learned more math, though. (I struggle with other
                          than very simple graphics). I'm doing what I can to rectify that
                          problem when I have time.

                          Anyway, I'd like to take this opportunity to personally thank
                          you for all your valuable contributions here. I feel I'm
                          better with C because of you (and others here). :-)

                          -Mike


                          Comment

                          • lawrence.jones@ugs.com

                            #14
                            Re: printf padding with alternate character?

                            Chris Torek <nospam@torek.n et> wrote:[color=blue]
                            >
                            > Well, yes; but I was referring to accountants' desire to print
                            > negative numbers in parentheses, or with the minus sign at the
                            > end, or with a "CR" (credit) or "DB" (debit) suffix, e.g.:[/color]

                            Or, even more obnoxiously, simply printing them in red, a practice which
                            thankfully went out of fashion when monochrome copiers became prevalent.

                            -Larry Jones

                            I've got an idea for a sit-com called "Father Knows Zilch." -- Calvin

                            Comment

                            Working...