Thread: printf that limits nr of chars printed

  1. #1
    zsaniK Kinasz's Avatar
    Join Date
    Jan 2003
    Posts
    222

    printf that limits nr of chars printed

    Is there an ansi/posix way to print a string but with a maximum number of characters, say if I only wanted to print the first 10 chars of a 20 char string.

    I have implemented my own function to do this, but I am just checking to see if there is a standard way?
    "Assumptions are the mother of all **** ups!"

  2. #2
    Registered User Draco's Avatar
    Join Date
    Apr 2002
    Posts
    463
    There isn't one that I've ever heard of.

  3. #3
    zsaniK Kinasz's Avatar
    Join Date
    Jan 2003
    Posts
    222
    cool, all i needed to know
    "Assumptions are the mother of all **** ups!"

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    #include <stdio.h>
    
    int main(void)
    {
       const char text[] = "A twenty-char string";
       printf("text = \"%.10s\"\n", text);
       return 0;
    }
    
    /* my output
    text = "A twenty-c"
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  5. #5
    Registered User Draco's Avatar
    Join Date
    Apr 2002
    Posts
    463
    very clever, I guess it's been too long since I took a good look at printf()

  6. #6
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    Neat trick never thought of that

  7. #7
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    To expand on Dave's suggestion since it is often desirable for it to be a variable number of characters:
    Code:
    #include <stdio.h>
    int main(void)
    {
      char str[] = "abcdefghijklmnopqrstuvwxyz";
      int count;
      for (count=0; count<sizeof str; count++)
        printf("%.*s\n", count, str);
      return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. creating counters and code not working
    By geekrockergal in forum C Programming
    Replies: 2
    Last Post: 02-05-2009, 12:50 AM
  2. saying hello and 1st question
    By darksys in forum C Programming
    Replies: 12
    Last Post: 10-31-2008, 02:58 PM
  3. Simple C question: user input to repeat a loop
    By evernaut in forum C Programming
    Replies: 2
    Last Post: 11-18-2006, 09:23 AM
  4. Printf to display chars
    By CodeMonkey in forum C++ Programming
    Replies: 4
    Last Post: 03-14-2002, 05:01 PM
  5. the bubble sort doesn't work help
    By Matt in forum C Programming
    Replies: 2
    Last Post: 12-13-2001, 06:14 PM