Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the %*s format specifier mean?

People also ask

What is the %s format specifier?

%s. It is used to print the strings. %ld. It is used to print the long-signed integer value. Let's understand the format specifiers in detail through an example.

What does S mean in Golang?

t - the word true or false. s - a string. v - default format. #v - Go-syntax representation of the value. T - a Go-syntax representation of the type of the value.

What does %u mean C?

unsigned specifier (%u) in C with Examples The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf().


It's used to specify, in a dynamic way, what the width of the field is:

  • The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

so "indent" specifies how much space to allocate for the string that follows it in the parameter list.

So,

printf("%*s", 5, "");

is the same as

printf("%5s", "");

It's a nice way to put some spaces in your file, avoiding a loop.


Don't use "%*s" on a buffer which is not NULL terminated (packed) thinking that it will print only "length" field.


The format specifier %4s outputs a String in a field width of 4—that is, printf displays the value with at least 4 character positions.

If the value to be output is less than 4 character positions wide, the value is right justified in the field by default.

If the value is greater than 4 character positions wide, the field width expands to accommodate the appropriate number of characters.

To left justify the value, use a negative integer to specify the field width.

References: Java™ How To Program (Early Objects), Tenth Edition


When used in printf and fprintf:

printf("%*s", 4, myValue); is equivalent to printf("%4s", myValue);

It displays the variable with minimum width, rest right-justified spaces. To left-justify the value, use a negative integer.

When used in scanf and sscanf:

/* sscanf example */
#include <stdio.h>

int main ()
{
  char sentence []="Rudolph is 12 years old";
  char str [20];
  int i;

  sscanf (sentence,"%s %*s %d",str,&i);
  printf ("%s -> %d\n",str,i);
  
  return 0;
}

Output:

Rudolph -> 12

It is used to ignore a string.