Skip to content Skip to sidebar Skip to footer

Write a Program That Reads a Date in the First Format and Prints It in the Second Format.

Printf Format Strings


By Alex Allain

Past default, C provides a great bargain of ability for formatting output. The standard display part, printf, takes a "format cord" that allows y'all to specify lots of information about how a program is formatted.

Note: if you are looking for information on formatting output in C++, take a look at formatting C++ output using iomanip.

Let'due south look at the anatomy of a format string followed by some brusque example programs to show the different settings in activeness. I won't include every single possible option--instead, my goal is to make information technology easy to understand the mini-language that you can use for creating format strings and teach yous how to use the common formatting y'all're well-nigh likely to need.

Anatomy of a Format String

When you make a call to printf, the basic idea is that you are going to provide a string of characters that has some literal characters and some elements that are to be replaced. For case, a string like:

"a b c"        

Will be printed literally as it appears. While information technology is sometimes enough to literally write into your code exactly what you want to print, you usually want to do something fancier--either introducing special characters using escape sequences or introducing variable values using format specifiers.

Escape Sequences

At that place are some characters that you cannot directly enter into a string. These are characters similar a newline, which must be represented using some special syntax. These are chosen escape sequences and look like this:

"a\nb\nc"        

Here, I've entered the newlines betwixt each letter, a, b and c. Each escape sequence starts with a backslash ('\') graphic symbol. The main escape sequences that you lot'll use are: \northward, to put a newline, and \t, to put in a tab. Since a backslash normally indicates the starting time of an escape sequence, if you lot want to put in an escape sequence you demand to use \\ to display a backslash:

"C:\\Plan Files\\World of Warcraft"        

is how you'd write a Windows path in C++.

There's one other advanced play tricks, which is that you tin write \<num> to display the ASCII character represented past the value num. This is useful if you lot desire to display a graphic symbol that y'all can't easily type on your keyboard, such as absolute messages. For example, \130 will print out an character (in some cases, depending on what your automobile is set upwardly to practise with extended ASCII characters.)

Format Specifiers

If yous want to innovate some variance into the output, yous do and so by indicating that external data is needed:

"We have %d cats"        

In this cord, the %d indicates that the value to exist displayed at that point in the cord needs to be taken from a variable. The % sign indicates that we are splicing some data into the string, and the d character indicates that nosotros are splicing in a decimal number. The part of the string that begins with % is called the format specifier. In order to actually become that number, we need to provide that value to printf:

printf( "We have %d cats", 3 );        

which volition display:

"We have 3 cats"        

All of the interesting formatting that you can do involves irresolute the values you put subsequently the % sign, which is the actual format.

The format for what appears about a % sign is:

%[flag][min width][precision][length modifier][conversion specifier]        

Well-nigh of these fields are optional, other than providing a conversion specifier, which you've already seen (for case, using %d to print out a decimal number).

Understanding this formatting is best done by working backward, starting with the conversion specifier and working outward. And then let'southward begin at the cease!

Conversion Specifier

The conversion specifier is the part of the format specifier that determines the basic formatting of the value that is to be printed.

Conversion specifiers for integers

If y'all want to print a decimal integer number in base 0, you lot'd use either d or i: %d or %i. If you want to print an integer in octal or hexadecimal y'all'd employ o for octal, or 10 for hexadecimal. If you want uppercase letters (A instead of a when printing out decimal x) then y'all can use Ten.

Conversion specifiers for floating point numbers

Displaying floating bespeak numbers has a ton of different options, best shown in a tabular array:

Specifier Description Example
f Display the floating point number using decimal representation 3.1415
e Display the floating signal number using scientific notation with e one.86e6 (same equally 1,860,000)
E Like e, but with a capital Eastward in the output one.86E6
one thousand Use shorter of the 2 representations: f or e 3.one or 1.86e6
G Like thou, except uses the shorter of f or E 3.1 or one.86E6

Okay, that wasn't also bad was it? Simply that nautical chart is kind of complicated. My recommendation: just use %yard, and it volition usually exercise what you desire:

printf( "%grand", 3.1415926 );        

which displays:

3.1515926        

or

printf( "%g", 93000000.0 );        

which displays

nine.3e+07        

Where scientific note is almost appropriate.

Displaying a Percent Sign

Since the percent sign is used to define format specifiers, there's a special format specifier that means "print the percent sign":

%%        

to simply print out a per centum sign.

Now, allow's walk through each of the dissimilar components of a format specifier.

Length Modifier

The length modifier is mayhap oddly-named; information technology does not modify the length of the output. Instead, it's what you utilize to specify the length of the input. Huh? Say y'all accept:

long double d = 3.1415926535; printf( "%thou", d );        

Hither, d is the input to printf; and what you lot're saying is that you want to print d equally an double; but d is non a double, it is a long double. A long double is likely to exist 16 bytes (compared to 8 for a double), and so the divergence matters. Try running that small snippet and you'll find that you get garbage output that looks something like this:

iv.94066e-324        

Remember, the bytes that are given to printf are existence treated like a double--but they aren't a double, they're a long double. The length is incorrect, and the results are ugly!

The length modifier is all virtually helping printf deal with cases where you're using unusually big (or unusually small) variables.

The best style to think almost length modifiers is to say: what variable blazon practice I have, and practice I need to use a length modifier for information technology? Here's a tabular array that should help you lot out:

Variable type Length Modifier Instance
brusque int, unsigned curt int h short int i = 3; printf( "%hd", i );
long int or unsigned long int 50 long int i = 3; printf( "%ld", i );
wide characters or strings l wchar_t* wide_str = L"Wide Cord"; printf( "%ls", wide_str );
long double L long double d = 3.1415926535; printf( "%Lg", d );

I'd like to brand special mention about the wide grapheme handling. If you write

wchar_t* wide_str = L"Wide String"; printf( "%s", wide_str );        

without the fifty, the event volition exist to print a single W to the screen. The reason is that broad characters are two bytes, and for simple ASCII characters like W, the second byte is 0. Therefore, printf thinks the cord is done! You must tell printf to expect for multibyte characters by adding the fifty: %ls.

(If you happen to be using wprintf, on the other paw, you tin simply utilize %south and it will natively treat all strings as wide grapheme strings.)

Precision

The "precision" modifier is written ".number", and has slightly different meanings for the different conversion specifiers (similar d or g).

For floating point numbers (eastward.g. %f), information technology controls the number of digits printed later on the decimal bespeak:

printf( "%.3f", 1.2 );        

will print

i.200        

If the number provided has more precision than is given, it will round. For instance:

printf( "%.3f", ane.2348 );        

will display as

ane.235        

Interestingly, for g and 1000, it will command the number of significant figures displayed. This will impact not simply the value later the decimal place only the whole number.

printf( "%.3f\northward%.3g\northward%.3f\northward%.3g\n", 100.2, 100.2, 3.1415926, 3.1415926 );        
100.200 // %.3f, putting three decimal places always 100     // %.3g, putting three meaning figures 3.142   // %.3f, putting 3 decimal places again 3.14    // %.3g, putting 3 significant figures        

For integers, on the other hand, the precision it controls the minimum number of digits printed:

printf( "%.3d", 10 );        

Volition impress the number ten with three digits:

010        

There'due south one special case for integers--if you specify '.0', then the number nil will accept no output:

printf( "%.0d", 0 );        

has no output!

Finally, for strings, the precision controls the maximum length of the cord displayed:

printf( "%.5s\n", "abcdefg" );        

displays but

"abcde"        

This is useful if you demand to make sure that your output does non become across a fixed number of characters.

Width

The width field is most the opposite of the precision field. Precision controls the max number of characters to print, width controls the minimum number, and has the same format every bit precision, except without a decimal point:

printf( "%5s\north", "abc" );        

prints

          abc        

The blank spaces go at the beginning, by default.

Y'all can combine the precision and width, if yous like: <width>.<precision>

printf( "%8.5f\n", 1.234 );        

prints

          1.23400        

(Note the leading space.)

Flag

The flag setting controls 'characters' that are added to a string, such whether to append 0x to a hexadecimal number, or whether to pad numbers with 0s.

The specific flag options are

The Pound Sign: #

Adding a # volition cause a '0' to be prepended to an octal number (when using the o conversion specifier), or a 0x to be prepended to a hexadecimal number (when using a ten conversion specifier). For most other conversion specifiers, adding a # will simply force the inclusion of a decimal point, even if the number has no fractional function.

printf( "%#x", 12 );        

results in

0xc        

being printed. Whereas

printf( "%x", 12 );        

results in but

c        

being printed.

The Goose egg Flag: 0

Using 0 will force the number to exist padded with 0s. This simply actually matters if you use the width setting to inquire for a minimal width for your number. For example, if y'all write:

printf( "%05d\northward", 10 );        

You would go:

00010        

The Plus Sign Flag: +

The plus sign will include the sign specifier for the number:

printf( "%+d\northward", 10 );        

Will print

+10        

The Minus Sign Flag: -

Finally, the minus sign volition cause the output to be left-justified. This is of import if you are using the width specifier and you want the padding to appear at the end of the output instead of the beginning:

printf( "|%-5d|%-5d|\due north", 1, 2 );        

displays:

|1    |2    |        

With the padding at the terminate of the output.

Combining it all together

For any given format specifier, yous can provide must always provide the per centum sign and the base of operations specifier. You can then include any, or all, of the flags, width and precision and length that yous desire. You tin even include multiple flags togeher. Here's a particularly complex case demonstrating multiple flags that would be useful for printing memory addresses as hexadecimal values.

printf( "%#010x\northward", 12 );        

The easiest way to read this is to first find the % sign and and so read right-to-left--the x indicates that nosotros are press a hexadecimal value; the 10 indicates nosotros desire 10 total characters width; the next 0 is a flag indicating we desire to pad with 0s intead of spaces, and finally the # sign indicates we want a leading 0x. Since nosotros start with 0x, this means nosotros'll have 8 digits--exactly the right amount for printing out a 32 bit memory accost.

The final result is:

0x0000000c        

Pretty sugariness!

Read more similar articles

More on printf format strings in C

Produce nice output in C++ using iomanip

andersondayinexce1983.blogspot.com

Source: https://www.cprogramming.com/tutorial/printf-format-strings.html

Post a Comment for "Write a Program That Reads a Date in the First Format and Prints It in the Second Format."