Write Programs That Read a Line of Input as a String and Print Every Second Letter of the String

Printf Format Strings


By Alex Allain

By default, C provides a neat deal of power for formatting output. The standard display function, printf, takes a "format string" that allows you to specify lots of information nigh how a plan is formatted.

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

Let'south wait at the anatomy of a format string followed by some brusque example programs to show the different settings in action. I won't include every unmarried possible option--instead, my goal is to brand information technology easy to sympathise the mini-language that yous can use for creating format strings and teach you how to use the common formatting you lot're most likely to need.

Beefcake of a Format String

When yous brand a call to printf, the basic thought 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 instance, a string like:

"a b c"        

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

Escape Sequences

There are some characters that y'all cannot directly enter into a string. These are characters like a newline, which must be represented using some special syntax. These are called escape sequences and await similar this:

"a\nb\nc"        

Hither, I've entered the newlines betwixt each letter, a, b and c. Each escape sequence starts with a backslash ('\') grapheme. The main escape sequences that you lot'll use are: \due north, to put a newline, and \t, to put in a tab. Since a backslash usually indicates the start of an escape sequence, if you desire to put in an escape sequence you lot need to use \\ to brandish a backslash:

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

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

There's 1 other advanced trick, which is that you can write \<num> to brandish the ASCII character represented by the value num. This is useful if you want to display a character that you tin can't easily type on your keyboard, such as absolute letters. For example, \130 will print out an character (in some cases, depending on what your auto is prepare to do with extended ASCII characters.)

Format Specifiers

If you desire to introduce some variance into the output, you do then by indicating that external information is needed:

"We have %d cats"        

In this string, the %d indicates that the value to exist displayed at that point in the string 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 we are splicing in a decimal number. The part of the string that begins with % is called the format specifier. In club to actually go that number, we need to provide that value to printf:

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

which will display:

"We have 3 cats"        

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

The format for what appears nigh a % sign is:

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

Most of these fields are optional, other than providing a conversion specifier, which you've already seen (for example, 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. So let's begin at the end!

Conversion Specifier

The conversion specifier is the function of the format specifier that determines the basic formatting of the value that is to exist printed.

Conversion specifiers for integers

If you lot want to impress a decimal integer number in base 0, you'd use either d or i: %d or %i. If you want to impress an integer in octal or hexadecimal you'd utilize o for octal, or x for hexadecimal. If you want uppercase messages (A instead of a when press out decimal 10) so you can use X.

Conversion specifiers for floating point numbers

Displaying floating signal numbers has a ton of different options, all-time shown in a table:

Specifier Clarification Example
f Brandish the floating signal number using decimal representation 3.1415
e Display the floating point number using scientific notation with e 1.86e6 (same as ane,860,000)
E Like e, but with a capital E in the output 1.86E6
thou Use shorter of the two representations: f or eastward 3.ane or 1.86e6
Thousand Like g, except uses the shorter of f or Due east three.1 or 1.86E6

Okay, that wasn't too bad was information technology? Only that chart is kind of complicated. My recommendation: only use %g, and it will usually do what you want:

printf( "%g", 3.1415926 );        

which displays:

3.1515926        

or

printf( "%g", 93000000.0 );        

which displays

ix.3e+07        

Where scientific notation is most appropriate.

Displaying a Pct Sign

Since the per centum sign is used to define format specifiers, at that place'southward a special format specifier that means "print the per centum sign":

%%        

to but print out a percent sign.

Now, let's walk through each of the different components of a format specifier.

Length Modifier

The length modifier is perhaps oddly-named; it does non modify the length of the output. Instead, it's what yous use to specify the length of the input. Huh? Say yous take:

long double d = three.1415926535; printf( "%thou", d );        

Here, d is the input to printf; and what you're saying is that yous want to print d as an double; but d is not a double, it is a long double. A long double is likely to exist sixteen bytes (compared to 8 for a double), and then the difference matters. Endeavour running that pocket-sized snippet and you'll find that you get garbage output that looks something similar this:

4.94066e-324        

Think, the bytes that are given to printf are beingness treated like a double--merely they aren't a double, they're a long double. The length is wrong, and the results are ugly!

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

The best way to think well-nigh length modifiers is to say: what variable type do I have, and do I need to employ a length modifier for it? Hither's a table that should help y'all out:

Variable type Length Modifier Case
brusque int, unsigned short int h brusk int i = iii; printf( "%hard disk drive", i );
long int or unsigned long int fifty long int i = 3; printf( "%ld", i );
wide characters or strings fifty wchar_t* wide_str = L"Wide String"; printf( "%ls", wide_str );
long double L long double d = 3.1415926535; printf( "%Lg", d );

I'd like to brand special mention nigh the broad graphic symbol handling. If you write

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

without the fifty, the result volition be to impress a single W to the screen. The reason is that wide characters are two bytes, and for elementary ASCII characters like W, the 2d byte is 0. Therefore, printf thinks the string is washed! You must tell printf to expect for multibyte characters past adding the l: %ls.

(If you happen to exist using wprintf, on the other hand, you tin can merely use %s and it volition natively treat all strings as broad character strings.)

Precision

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

For floating point numbers (e.g. %f), it controls the number of digits printed after the decimal point:

printf( "%.3f", 1.two );        

will impress

one.200        

If the number provided has more than precision than is given, it volition circular. For example:

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

volition brandish every bit

ane.235        

Interestingly, for m and Yard, it will control the number of significant figures displayed. This volition impact not just the value after the decimal place but the whole number.

printf( "%.3f\northward%.3g\n%.3f\n%.3g\due north", 100.2, 100.ii, 3.1415926, three.1415926 );        
100.200 // %.3f, putting iii decimal places ever 100     // %.3g, putting three significant figures 3.142   // %.3f, putting 3 decimal places once more three.14    // %.3g, putting 3 significant figures        

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

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

Volition print the number 10 with three digits:

010        

There's one special example for integers--if y'all specify '.0', and so the number zero will take no output:

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

has no output!

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

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

displays merely

"abcde"        

This is useful if y'all demand to brand certain that your output does not go across a stock-still number of characters.

Width

The width field is well-nigh the contrary of the precision field. Precision controls the max number of characters to print, width controls the minimum number, and has the same format as precision, except without a decimal betoken:

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

prints

          abc        

The bare spaces go at the beginning, by default.

You can combine the precision and width, if you like: <width>.<precision>

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

prints

          1.23400        

(Annotation the leading space.)

Flag

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

The specific flag options are

The Pound Sign: #

Adding a # will 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, fifty-fifty if the number has no fractional part.

printf( "%#10", 12 );        

results in

0xc        

being printed. Whereas

printf( "%x", 12 );        

results in simply

c        

being printed.

The Zero Flag: 0

Using 0 will force the number to be padded with 0s. This only really matters if you use the width setting to inquire for a minimal width for your number. For instance, if yous write:

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

You would become:

00010        

The Plus Sign Flag: +

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

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

Volition print

+10        

The Minus Sign Flag: -

Finally, the minus sign will cause the output to exist left-justified. This is of import if you are using the width specifier and you want the padding to announced at the stop of the output instead of the start:

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

displays:

|1    |2    |        

With the padding at the finish of the output.

Combining it all together

For any given format specifier, you lot tin can provide must always provide the percent sign and the base specifier. You can then include whatsoever, or all, of the flags, width and precision and length that you lot want. You can even include multiple flags togeher. Hither'due south a specially circuitous case demonstrating multiple flags that would be useful for printing memory addresses as hexadecimal values.

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

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

The concluding result is:

0x0000000c        

Pretty sweet!

Read more than like manufactures

More on printf format strings in C

Produce nice output in C++ using iomanip

linappich.blogspot.com

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

0 Response to "Write Programs That Read a Line of Input as a String and Print Every Second Letter of the String"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel