Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

can I truncate a string with printf

Status
Not open for further replies.

pjb

Programmer
May 1, 2001
148
US
I am formatting an output record with printf. The argument type is %15s, but it is possible that the input may be longer than 15. Is there anyway to code the %s argument to truncate the field, or do I need extra code to assure the field is a max of 15?
 
Try this :
sprintf(record.field, "%.15s", stringptr);
/JOlesen
 
hmm..

yes.. you can specify the length of the string in your printf for formatting records.. you need to include a '.'followed by the num of chars in the string you want to print.

here is an example:


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

#define MAX 200

int main (int argc, char *argv[]) {
int i;
char *buff;

buff = (char*)malloc(MAX);
memset (buff, '\0',sizeof(buff));
for (i=1; i<argc; i++) strcat (buff,argv);
printf (&quot;%.5s&quot;,buff);
return 0;
}
 
hi,

I always use

printf(&quot;%*.*s&quot;, x, x, string ) ;

It never fails !

bye
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top