simple printf question

Discussion in 'C Programming' started by Bint, Oct 17, 2007.

  1. Bint

    Bint Guest


    I have a giant string buffer, and I want to print out small chunks of it at
    a time. How do I print out, say 20 characters of a string?

    Is it like this?


    I can change the start point of the string, I just don't know how to tell it
    to only print out X number of characters from it.
    Bint, Oct 17, 2007
    1. Advertisements

  2. Bint said:
    printf("%.20s", mystring);

    Note the dot in the format specifier.

    Covered in K&R2 p244.
    Richard Heathfield, Oct 17, 2007
    1. Advertisements

  3. Bint

    Tor Rustad Guest

    printf("%.*s", len, mystring);
    Tor Rustad, Oct 18, 2007
  4. Bint

    husterk Guest


    Another more flexible method would be to snprintf() your larger string
    into a temporary string buffer and then output the temporary buffer
    using a standard unformatted printf(). This will allow you to
    dynamically change the size of your output string by supplying a
    variable length for your temporary string buffer in the snprintf()
    routine (which cannot be accomplished using the "%.20s" method
    described by Richard.

    husterk, Oct 18, 2007
  5. husterk said:

    There is really no need to go to all that trouble.

    printf("%.*s\n", nchars, mystring);

    Again, this is documented very clearly in K&R2.
    Richard Heathfield, Oct 18, 2007
  6. Be careful to cast nchar as (int) if it has a different type, such as
    Charlie Gordon, Oct 20, 2007
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.