tags:

views:

97

answers:

2
+1  Q: 

Limit Output in C

In C, I would like to limit the string to the first 8 characters. For example, I have:

char out = printf("%c", str);

How can I make it so it only returns the first 8 characters?

+9  A: 

You can limit the length by setting the precision in the format specifier:

printf("%.8s", str);

This will print up to eight characters from the null-terminated string pointed-to by str. If the length of str is less than eight characters, then it will print the entire string.

Note that the format specifier for a null-terminated string is %s, not %c (%c is to print a single char), and that printf returns an int (the total number of characters printed), not a char.

James McNellis
Thanks dude. Is there a way to get rid of all the spaces?
Tech163
Nvm. I've changed it to printf("%.s", hexencode(c)); Thanks for your help.
Tech163
You can also specify the max length at runtime with the * specifier: `printf("%.*s", max_len, str);`
R Samuel Klatchko
A: 

No

That is incorrect. tabular printing "%8s" pads up to say 8 spaces, as in the example given. It does not truncate. ISOC99. If this is a windows only thing, okay, MS ignores the world on lots of things. If the length of the string is longer than the tabulation then the full string prints. See:

int main()
{
  char tmp[]="123456789";
  printf("1  %1s\n", tmp);
  printf("2  %2s\n", tmp);
  printf("4  %4s\n", tmp);
  printf("8  %8s\n", tmp);
  printf("16 %16s\n", tmp);
  printf("32 %32s\n", tmp);
  return 0;
}

output from gcc 3.4.2 on Solaris 5.9:

> ./a.out                   
1  123456789                       
2  123456789                       
4  123456789                       
8  123456789                       
16        123456789                
32                        123456789

sprintf() will duplicate and truncate a string then it can be sent to printf. Or if you don't care about the source string:

char * trunc(char *src, int len)
{
    src[len]=0x0;
    return src;
}

References: INTERNATIONAL STANDARD ©ISO/IEC ISO/IEC 9899:TC2, WG14/N1124 Committee Draft — May 6, 2005

jim mcnamara
Assuming you meant this as a response to my answer, I believe you missed the `.` in the format specifier: `%8s` sets the *minimum* width to eight characters; `%.8s` sets the *maximum* width to eight characters (these are, respectively, the _width_ and _precision_ modifiers of the format specifier). There is nothing platform-specific to this behavior--it's part of the specification of the C language (and C++, since it includes the C standard library).
James McNellis
You are correct - I DID miss the .
jim mcnamara