How to Use Conversion Characters in the C Language's printf() Function

In the C language, if you want to print the value of a variable to the screen, you'll likely use the printf() function. To do so, you need to include a conversion character — a placeholder of sorts — in the literal string that you want to print. That conversion character is then replaced by the variable or value you indicate later in the command.


Consider this example:


#include <stdio.h>
int main()
{
int age;
float distance;
age = 27;
distance = 319.125;
printf("The alien is %d years old and\n",age);
printf("comes from a planet %f microns away.\n",distance);
return(0);
}

This source code declares two variables — age and distance — and then assigns to them the values 27 and 319.125, respectively. In the printf() functions, the %d and %f in the statements' strings are conversion characters. This is a glimpse into the power of printf(); the %d and %f are replaced by an integer and a floating-point value (respectively) specificed later in the printf() functions' parentheses. In this case, the values to substitute are the variables age and distance.


Save this code, compile it, and run it, and you should see this:


The alien is 27 years old and comes from a planet 319.125 microns away.

You need to be sure that the conversion code you include in the string statement matches the number type that you assigned to the variable when you declared it or you might not be happy with the results. The following table lists the conversion codes in the C language:



































































Conversion CharacterDisplays
%%The percent character, %
%cSingle character (char) value
%dInteger (int, class="code">short int, long int)
value
%eFloating-point (float or class="code">double) value in scientific notation with a
little E
%EFloating-point (float or class="code">double) value in scientific notation with a big
E
%fFloating-point (float or class="code">double) value in decimal notation
%gEither %f or class="code">%e is used, depending on which is shorter
%GEither %F or class="code">%E is used, depending on which is shorter
%iInteger (int, class="code">short int, long int)
value
%oUnsigned octal value (no leading 0)
%pMemory location or address in hexadecimal (pointer)
%sString constant or variable (char
*
)
%uUnsigned integer (unsigned int, class="code">unsigned short int, unsigned
long int
) value
%xUnsigned hexadecimal value, lowercase a–f, no leading 0
or x
%XUnsigned hexadecimal value, uppercase A–F, no leading 0
or X










dummies

Source:http://www.dummies.com/how-to/content/how-to-use-conversion-characters-in-the-c-language.html

No comments:

Post a Comment