Keil Logo

GENERAL: LIMIT STRING OUTPUT IN PRINTF USING %S


Information in this article applies to:

  • C51 Version 7 or higher
  • CX51 Version 7 or higher
  • C251 Version 2 or higher
  • C166 Version 4 or higher
  • MDK-ARM any Version

QUESTION

I am using the following sprintf statement to limit a string output. However it outputs more than the 5 characters specified. In fact, it even outputs a new line ('\n') sequence that is part of str.

  sprintf (buf, "string = %5s", str)

Is this a problem with the Keil C Compiler?

ANSWER

No, this is standard ANSI behaviour. You need to specify a precision (number after the dot '.') in the %s format parameter to limit size of the string printed. The precision field is a non-negative number that specifies the number of characters to print.

Example:

  sprintf (buf, "string = %.5s", str)

Using this format string, the string passed by str will be truncated after five characters.

MORE INFORMATION

  • Refer to printf in the Cx51 User's Guide.
  • Refer to printf in the C166 User's Guide.
  • Refer to printf in the CARM User's Guide.
  • You may wish to refer to a good General Programming Book like The C Programming Language by Kernigan & Ritchie.

Last Reviewed: Thursday, December 12, 2013


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.