How to Read Blank Space in C++
Printf Format Strings
By Alex Allain
Past default, C provides a peachy bargain of power for formatting output. The standard display function, printf, takes a "format string" that allows you to specify lots of information near how a program is formatted.
Notation: if you are looking for information on formatting output in C++, take a look at formatting C++ output using iomanip.
Allow's look at the anatomy of a format string followed by some short case programs to show the unlike settings in action. I won't include every unmarried possible choice--instead, my goal is to go far like shooting fish in a barrel to understand the mini-language that you lot can use for creating format strings and teach you how to employ the common formatting y'all're most likely to need.
Anatomy of a Format String
When you make a telephone 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 similar:
"a b c"
Volition be printed literally as information technology appears. While it 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
In that location are some characters that you lot cannot straight enter into a string. These are characters like 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 between each letter, a, b and c. Each escape sequence starts with a backslash ('\') grapheme. The principal escape sequences that yous'll use are: \n, to put a newline, and \t, to put in a tab. Since a backslash normally indicates the start of an escape sequence, if you desire to put in an escape sequence yous need to utilize \\ to display a backslash:
"C:\\Program Files\\World of Warcraft"
is how you'd write a Windows path in C++.
At that place's ane other avant-garde trick, which is that you can write \<num> to display the ASCII character represented by the value num. This is useful if you want to display a character that yous tin't easily blazon on your keyboard, such as accented letters. For example, \130 will print out an graphic symbol (in some cases, depending on what your automobile is set up to exercise with extended ASCII characters.)
Format Specifiers
If y'all want to introduce some variance into the output, you do so by indicating that external data is needed:
"We have %d cats"
In this string, the %d indicates that the value to be 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 cord, and the d character indicates that we are splicing in a decimal number. The function of the string that begins with % is chosen the format specifier. In order to really go that number, we need to provide that value to printf:
printf( "We have %d cats", 3 );
which will display:
"We have iii cats"
All of the interesting formatting that you tin can practice involves changing the values yous put later on the % sign, which is the bodily format.
The format for what appears virtually a % sign is:
%[flag][min width][precision][length modifier][conversion specifier]
Virtually of these fields are optional, other than providing a conversion specifier, which you've already seen (for example, using %d to impress out a decimal number).
Understanding this formatting is best done by working backward, starting with the conversion specifier and working outward. So let'southward begin at the finish!
Conversion Specifier
The conversion specifier is the office of the format specifier that determines the basic formatting of the value that is to be printed.
Conversion specifiers for integers
If you want to print a decimal integer number in base 0, you'd use either d or i: %d or %i. If y'all want to print an integer in octal or hexadecimal you'd use o for octal, or ten for hexadecimal. If y'all want capital letter letters (A instead of a when printing out decimal 10) then you tin can use X.
Conversion specifiers for floating betoken numbers
Displaying floating point numbers has a ton of different options, best shown in a table:
| Specifier | Description | Example |
|---|---|---|
| f | Display the floating point number using decimal representation | three.1415 |
| eastward | Display the floating indicate number using scientific notation with e | 1.86e6 (same as 1,860,000) |
| E | Similar due east, but with a capital E in the output | one.86E6 |
| g | Use shorter of the two representations: f or e | three.1 or 1.86e6 |
| Grand | Similar g, except uses the shorter of f or Eastward | 3.1 or i.86E6 |
Okay, that wasn't as well bad was information technology? Simply that chart is kind of complicated. My recommendation: just use %thousand, and information technology will usually do what you desire:
printf( "%m", 3.1415926 );
which displays:
3.1515926
or
printf( "%thou", 93000000.0 );
which displays
9.3e+07
Where scientific notation is almost appropriate.
Displaying a Pct Sign
Since the per centum sign is used to define format specifiers, there's a special format specifier that means "print the percent sign":
%%
to simply print out a percent sign.
Now, allow'due south walk through each of the dissimilar components of a format specifier.
Length Modifier
The length modifier is perhaps oddly-named; it does not modify the length of the output. Instead, it'southward what you use to specify the length of the input. Huh? Say yous take:
long double d = 3.1415926535; printf( "%g", d );
Here, d is the input to printf; and what you're saying is that you desire to print d as an double; but d is not a double, information technology is a long double. A long double is likely to be xvi bytes (compared to 8 for a double), then the deviation matters. Attempt running that small-scale snippet and you'll find that you get garbage output that looks something like this:
4.94066e-324
Remember, the bytes that are given to printf are being treated like a double--but they aren't a double, they're a long double. The length is wrong, and the results are ugly!
The length modifier is all most helping printf bargain with cases where you're using unusually large (or unusually pocket-sized) variables.
The best mode to retrieve about length modifiers is to say: what variable type do I have, and do I need to use a length modifier for it? Here's a table that should help yous out:
| Variable type | Length Modifier | Instance |
|---|---|---|
| short int, unsigned brusk int | h | curt int i = 3; printf( "%hd", i ); |
| long int or unsigned long int | l | long int i = 3; printf( "%ld", i ); |
| broad characters or strings | l | wchar_t* wide_str = Fifty"Wide String"; printf( "%ls", wide_str ); |
| long double | L | long double d = 3.1415926535; printf( "%Lg", d ); |
I'd similar to brand special mention about the broad character treatment. If you write
wchar_t* wide_str = L"Wide String"; printf( "%s", wide_str );
without the l, the result volition be to impress a unmarried Due west to the screen. The reason is that wide characters are two bytes, and for uncomplicated ASCII characters like West, the 2d byte is 0. Therefore, printf thinks the string is done! Yous must tell printf to wait for multibyte characters by adding the l: %ls.
(If yous happen to be using wprintf, on the other mitt, you can simply use %s and information technology will natively care for all strings as wide character strings.)
Precision
The "precision" modifier is written ".number", and has slightly unlike meanings for the different conversion specifiers (like d or g).
For floating indicate numbers (e.g. %f), information technology controls the number of digits printed after the decimal bespeak:
printf( "%.3f", 1.ii );
will print
1.200
If the number provided has more precision than is given, it will round. For example:
printf( "%.3f", ane.2348 );
volition display equally
1.235
Interestingly, for grand and G, it will control the number of significant figures displayed. This volition impact not just the value afterwards the decimal identify but the whole number.
printf( "%.3f\northward%.3g\n%.3f\northward%.3g\north", 100.ii, 100.two, three.1415926, 3.1415926 );
100.200 // %.3f, putting three decimal places ever 100 // %.3g, putting 3 meaning figures 3.142 // %.3f, putting 3 decimal places once more 3.fourteen // %.3g, putting 3 significant figures
For integers, on the other paw, the precision information technology controls the minimum number of digits printed:
printf( "%.3d", 10 );
Will print the number ten with three digits:
010
At that place's one special case for integers--if y'all specify '.0', then the number nothing will have no output:
printf( "%.0d", 0 );
has no output!
Finally, for strings, the precision controls the maximum length of the cord displayed:
printf( "%.5s\north", "abcdefg" );
displays only
"abcde"
This is useful if you need to brand sure that your output does non become across a fixed number of characters.
Width
The width field is almost the reverse 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 signal:
printf( "%5s\northward", "abc" );
prints
abc
The bare spaces go at the first, past default.
You can combine the precision and width, if you like: <width>.<precision>
printf( "%8.5f\due north", 1.234 );
prints
i.23400
(Note the leading space.)
Flag
The flag setting controls 'characters' that are added to a cord, 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 exist prepended to an octal number (when using the o conversion specifier), or a 0x to be prepended to a hexadecimal number (when using a x conversion specifier). For about other conversion specifiers, adding a # will simply force the inclusion of a decimal point, even if the number has no fractional part.
printf( "%#x", 12 );
results in
0xc
existence printed. Whereas
printf( "%x", 12 );
results in only
c
being printed.
The Zero Flag: 0
Using 0 volition force the number to be padded with 0s. This simply really matters if you use the width setting to ask for a minimal width for your number. For example, if you write:
printf( "%05d\n", x );
Y'all would go:
00010
The Plus Sign Flag: +
The plus sign volition include the sign specifier for the number:
printf( "%+d\n", 10 );
Volition print
+ten
The Minus Sign Flag: -
Finally, the minus sign will cause the output to be left-justified. This is important if yous are using the width specifier and you want the padding to appear at the stop of the output instead of the showtime:
printf( "|%-5d|%-5d|\n", ane, 2 );
displays:
|1 |ii |
With the padding at the end of the output.
Combining it all together
For whatever given format specifier, you can provide must e'er provide the percent sign and the base specifier. Y'all can then include any, or all, of the flags, width and precision and length that you lot want. You can fifty-fifty include multiple flags togeher. Here's a particularly complex example demonstrating multiple flags that would be useful for printing retentivity addresses as hexadecimal values.
printf( "%#010x\due north", 12 );
The easiest way to read this is to kickoff observe the % sign then read right-to-left--the x indicates that we are printing a hexadecimal value; the 10 indicates we desire x total characters width; the adjacent 0 is a flag indicating nosotros want to pad with 0s intead of spaces, and finally the # sign indicates we want a leading 0x. Since we start with 0x, this means we'll have eight digits--exactly the correct amount for press out a 32 flake retentivity address.
The last result is:
0x0000000c
Pretty sweet!
Read more like manufactures
More on printf format strings in C
Produce nice output in C++ using iomanip
pridemorefrob1971.blogspot.com
Source: https://www.cprogramming.com/tutorial/printf-format-strings.html
0 Response to "How to Read Blank Space in C++"
Post a Comment