Code Tricks: The * I/O modifier

The * character can be used within the format strings of both printf and scanf. Instead of using a number for the field width in a specifier in a printf statement, you can use *. The value still has to be supplied, but this way it is supplied with a value passed to printf. For example:

int num, width;
printf(“%*d”, width, num);

This uses the value supplied by the variable width to specify the field width. The * in scanf serves another purpose. When placed between the % and the type specifier, it causes scanf to skip over the corresponding input. For example:

int num;
char ch;
scanf(“%d%*c%c”, &num, &ch);

If the user enters “12 b”, this causes the integer 12 to be stored in the variable num, the next character (a space) is discarded, and the character “b” to be stored in the variable ch. This deals nicely with the problem of %c reading the next character in the buffer, which in this case is a space.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s