Lesson 03: Basic I/O Function
Input and output are the basic elements of the program. The computer needs to input the data, process the data, then output the results. The basic input and output are keyboard and screen: read data from the keyboard, and print the results on the screen. This lesson describes the basic input and output functions in C and C++. Lesson 16 will introduce input and output functions for file access.
3.1 Basic Input/Output in C
C language has standard libraries that allow input and output in a program. The stdio.h or standard input/output library in C that has methods for input and output. Therefore, whenever using a function from this library, you should include it in your source file.
#include <stdio.h>
Character I/O
getchar()
#include <stdio.h>
int getchar(void);
The getchar() function proved convenient when you wanted to read data a single character at a time, and it returns the next character from stdin. The character is read as an unsigned char that is converted to an integer.
Example:
char ch; ch = getchar(); // Read a single character into the variable ch printf("You entered the character '%c'\n", ch);
putchar()
#include <stdio.h>
int putchar(int ch);
The putchar() function writes the character contained in the least significant byte of ch to stdout. It is functionally equivalent to putc(ch, stdout). Because character arguments are elevated to the integer at the time of the call, you can use character values as arguments to putchar().
The putchar() function returns the character written if successful or EOF if an error occurs.
Example:
char ch = 'A'; putchar(ch); // Display the character ch to the console
gets()
#include <stdio.h>
char *gets(char *str);
The gets() function reads characters from stdin and places them into the character array pointed to by str. Characters are read until a newline or an EOF is received. The newline character is not made part of the string; instead, it is translated into a null to terminate the string.
If successful, gets() returns str; a null pointer is returned upon failure. If a read error occurs, the contents of the array pointed by str are indeterminate. Because a null pointer will be returned either when an error has occurred or when the end of the file is reached, you should use feof() or ferror() to determine what has actually happened.
There is no way to limit the number of characters that gets() will read, which means that the array pointed to by str could be overrun. Thus, this function is inherently dangerous. Its use should be limited to sample programs or utilities for your own use. It should not be used for production code.
Example:
char str[100]; gets(str); // Read a string from the console into the character array str printf("You entered the string: '%s'\n", str);
puts()
#include <stdio.h>
int puts(const char *str);
The puts() function writes the string pointed to by str to the standard output device. The null terminator is translated to a newline.
The puts() function returns a non-negative value if successful and an EOF upon failure.
Example:
char str[] = "Hello, world!"; puts(str); // Display the string str to the console
Comparison of gets() and puts() with getchar() and putchar()
- gets() and puts() deal with entire strings, while getchar() and putchar() handle single characters.
- gets() is deprecated due to security concerns, while getchar() and putchar() are considered safe.
- puts() adds a newline character to the output, while putchar() does not.
The getchar() and putchar() functions provide basic character I/O operations, while the gets() and puts() functions simplify string input and output. However, gets() is considered unsafe and should be avoided.
Example 01: getchar() and putchar()
#include <stdio.h> int main( ) { int c; printf( "Enter a value: "); c = getchar( ); printf( "\nYou entered: "); putchar( c ); return 0; }
When the above code is compiled and executed, it waits for users to input some text and press enter, the program processes and reads on a single character and displays it as follows:
Enter a value: This is an example
You entered: T
Example 02: gets() and puts()
#include <stdio.h> int main( ) { char str[100]; printf( "Enter a value: "); gets( str ); printf( "\nYou entered: "); puts( str ); return 0; }
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads the complete line till the end, and displays it as follows:
Enter a value: This is an example
You entered: This is an example
Formatted I/O
printf()
#include <stdio.h>
int printf(const char *format, ...);
The printf() function writes to stdout the arguments that comprise the argument list as specified by the string pointed to by format.
The string pointed to by format consists of two types of items.
- The first type is made up of characters that will be printed on the screen.
- The second type contains format specifiers that define how arguments are displayed.
A format specifier begins with a percent sign (%) followed by the format code. There must be the same number of arguments as there are format specifiers, and the format specifiers and the arguments are matched in order. For example, the following printf() call displays "Hi c 10 there!":
printf("Hi %c %d %s", 'c', 10, "there!");
Figure 4.1 shows how the elements of the printf() statement work together to generate the final result.
Figure 4.1: printf() Structure
The output is undefined if there are insufficient arguments to match the format specifiers. The remaining arguments are discarded if there are more arguments than format specifiers.
The printf() function returns the number of characters printed. A negative return value indicates that an error has taken place.
The general format of a printf() format specifiers is as follows:
%[flags][width][.prec][type]code
Optional fields are enclosed in brackets and must appear in the order shown.
The tables of format for printf() function
flag | Meaning |
---|---|
- | Left-justify value |
+ | Precede value with + or - |
[space] | Precede positive value with a space character |
0 | Zero fill numbers |
# | Precede octal value with 0, hexadecimal value with 0x (or 0X); display decimal point for floats; level trailing zeros for %g or %G format. |
width | prec | Meaning |
---|---|---|
number | Minimum size of the field | |
* | Take the next argument to printf() as the size of the field. | |
.number |
|
|
.* | Take the next argument to printf() as precision (and interpret as indicated in the preceding row) |
type | Meaning |
---|---|
hh | Display integer argument as a character |
h | Display short int (*) |
l | Display long int (*) |
ll | Display long long int (*) |
L | Display long double (*) |
j | Display intmax_t or uintmax_t value (*) |
t | Display ptrdiff_t value (*) |
z | Display size_t value (*) |
Note: (*) These specifiers can also be placed in front of the %n format to indicate the corresponding pointer argument is of the specified type.
code | Meaning |
---|---|
a | Floating-point number in the hexadecimal output in the form 0xh.hhhhp±d. |
A | Floating-point number in the hexadecimal output in the form 0Xh.hhhhp±d. |
c | Single character |
d | Signed decimal integer |
i | Signed decimal integer |
e | Floating-point number in exponential (scientific notation) format (lowercase e) |
E | Floating-point number in exponential (scientific notation) format (uppercase E) |
f | Floating-point number, to size decimal places by default |
F | Floating-point number, to size decimal places by default |
g | Floating-point number in %e or %f format, whichever is shorter |
G | Floating-point number in %E or %F format, whichever is shorter |
o | Unsigned octal integer |
s | A string of character (Null-terminated character string) |
u | Unsigned decimal integer |
x | Hexadecimal integer, using a~f |
X | Hexadecimal integer, using A~F |
p | Display a pointer |
n | Don't print anything; store the number of characters written so far by this call inside the int pointed to by the corresponding argument (see the note from Table type) |
% | Print a percent sign (%) |
The datatype and printf() code
Data Type | Constant Examples | printf() Code |
---|---|---|
char | 'a','\n' | %c |
bool,_Bool | 0, 1 | %i, %u |
short int | — | %hi, %hx, %ho |
unsigned short int | — | %hu, %hx, %ho |
int | 12, -97, 0xFFE0, 0177 | %i, %x, %o |
unsigned int | 12u, 100u, 0xFFu | %u, %x, %o |
long int | 12L, -2001, 0xffffL | %li, %lx, %lo |
unsigned long int | 12UL, 100ul, 0xffeeUL | %lu, %lx, %lo |
long long long | 0xff00fffLL, 512ll | %lli, %llx, %llo |
unsigned long long int | 12ull, oxffeeULL | %llu, %llx, %llo |
float | 12.34f, 3.1e-5f, 0x1.5p10, 0x1p-1 | %f, %e, %g, %a |
double | 12.34, 3.1e-5, 0x.1p3 | %f, %e, %g, %a |
long double | 12.34l, 3.1e5l | %Lf, %Le, %Lg |
Example of print()
#include <stdio.h> int main (void) { char c = 'X'; char s[] = "abcdefghijklmnopqrstuvwxyz"; int i = 425; short int j = 17; unsigned int u = 0xf179U; long int l = 75000L; long long int L = 0x1234567812345678LL; float f = 12.978F; double d = -97.4583; char *cp = &c; int *ip = &i; int c1, c2; printf ("Integers:\n"); printf ("%d <%5d> <%05d> <%-5d> <%+5d>\n", i, i, i, i); printf ("%i %o %x %u\n", i, i, i, i); printf ("%x %X %#x %#X\n", i, i, i, i); printf ("%+i % i %07i %.7i\n", i, i, i, i); printf ("%i %o %x %u\n", j, j, j, j); printf ("%i %o %x %u\n", u, u, u, u); printf ("%ld %lo %lx %lu\n", l, l, l, l); printf ("%lli %llo %llx %llu\n", L, L, L, L); printf ("\nFloats and Doubles:\n"); printf ("%f %e %g\n", f, f, f); printf ("%.2f %.2e\n", f, f); printf ("%.0f %.0e\n", f, f); printf ("%7.2f %7.2e\n", f, f); printf ("%f %e %g\n", d, d, d); printf ("%.*f\n", 3, d); printf ("%*.*f\n", 8, 2, d); printf ("\nCharacters:\n"); printf ("%c\n", c); printf ("%3c%3c\n", c, c); printf ("%x\n", c); printf ("\nStrings:\n"); printf ("%s\n", s); printf ("%.5s\n", s); printf ("%30s\n", s); printf ("%20.5s\n", s); printf ("%-20.5s\n", s); printf ("\nPointers:\n"); printf ("%p %p\n\n", ip, cp); printf ("This%n is fun.%n\n", &c1, &c2); printf ("c1 = %i, c2 = %i\n", c1, c2); return 0; }
// The results Integers: 425 < 425> <00425> <425 > < +425> 425 651 1a9 425 1a9 1A9 0x1a9 0X1A9 +425 425 0000425 0000425 17 21 11 17 61817 170571 f179 61817 75000 222370 124f8 75000 1311768465173141112 110642547402215053170 1234567812345678 1311768465173141112 Floats and Doubles: 12.978000 1.297800e+01 12.978 12.98 1.30e+01 13 1e+01 12.98 1.30e+01 -97.458300 -9.745830e+01 -97.4583 -97.458 -97.46 Characters: X X X 58 Strings: abcdefghijklmnopqrstuvwxyz abcde abcdefghijklmnopqrstuvwxyz abcde abcde Pointers: 0x7ffc8ae934e4 0x7ffc8ae934e1 This is fun. c1 = 9, c2 = 17
scanf()
#include <stdio.h>
int scanf(const char *format, ...);
The scanf() function is a general-purpose input routine that reads the stream stdin and stores the information in the variables pointed to in its argument list. It can read all the built-in data types and automatically converts them into the proper internal format.
The control string pointed to by format consists of three classifications of characters:
- Format specifiers
The input format specifiers begin with a % sign and tell scanf() what type of data is to be read next. - Whitespace characters
A whitespace character in the format string causes scanf() to skip over zero or more whitespace characters in the input stream. A whitespace character is either a blank space, a horizontal tab character ('\t'), a vertical tab ('\v'), a carriage return ('\r'), a newline ('\n'), or a form-feed character ('\f'). In essence, one whitespace character in the control string will cause scanf() to read, but not store, any number (including zero) of whitespace characters up to the first non-whitespace character. - Nonwhitespace characters
A non-whitespace character in the format string causes scanf() to read and discard a matching character. For example, "%d,%d" causes scanf() first to read an integer, then read and discard a comma, and finally read another integer. If the specified character is not found, scanf() will terminate.
All the variables that receive values through scanf() must be passed by their addresses. This means that all arguments must be pointers to the variables.
The scanf() function returns a number equal to the number of fields that were successfully assigned values. This number will not include read but not assigned fields because the * modifier was used to suppress the assignment. EOF is returned if an error occurs before the first field is assigned.
The general format of a scanf() format specifier is as follows:
%[modifier]code
Optional fields are enclosed in brackets and must appear in the order shown.
The tables of format for scanf() function
Modifier | Meaning |
---|---|
* | The field is to be skipped and not assigned |
size | Maximum size of the input field |
hh | Value is to be stored in a signed or unsigned char |
h | Value is to be stored in a short int |
l | Value is to be stored in a long int, double, or wchar_t |
j, z, or t | Value is to be stored in a size_t(%J), ptrdiff_t(%z), intmax_t, or uintmax_t(%t) |
ll | Value is to be stored in a long long int |
L | Value is to be stored in a long double |
code | Meaning |
---|---|
a | Read a floating-point value |
A | Same as %a |
c | Read a signed character |
d | Read a decimal integer |
i | Read an integer in either decimal, octal, or hexadecimal format |
e | Read a floating-point number |
E | Same as %e |
f | Read a floating-point number |
F | Same as %f |
g | Read a floating-point number |
G | Same as %g |
o | Read an octal number |
s | Read a string |
x | Read a hexadecimal number |
X | Same as %x |
p | Read a pointer |
n | Receive an integer value equal to the number of characters read so far |
u | Read an unsigned decimal integer |
[] | Scan for a set of characters |
% | Read a percent sign |
Example of scanf()
In the input stream, items must be separated by spaces, tabs, or newlines. Punctuation such as commas, semicolons, and the like do not count as separators. This means that:
scanf("%d%d", &r, &c);
will accept an input of 10 20 but fail with 10,20.
A * placed after the % and before the format code will read data of the specified type but suppress its assignment. Thus, the following command:
scanf("%d%*c%d", &x, &y);
given the input 10/20, will put the value 10 into x, discard the divide sign, and give y the value 20.
Although spaces, tabs, and newlines are used as field separators, when reading a signal character, these are read like any other character. For example, given an input stream of x y.
scanf("%c%c%c", &a, &b, &c);
will return with the character x in a, a space in b, and the character y in c.
An * can be used to skip fields. If the scanf() call
scanf("%i %5c %*f %s", &i1, text, str);
is executed and given the following line of text as input
144abcde 736.55 (wine and cheese)
the value 144 is stored in i1; the five characters abcde are stored in the character array text; the floating value 736.55 is matched but not assigned; and the character string "(wine" is stored in str, terminated by a null. The next call to scanf() pick up where the last one left off. So, a sequent call such as
scanf("%s %s %i", str2, str3, &i2);
has the effect of storing the character string "and" in str2 and the string "cheese)" in str3, and causes the function to wait for an integer value to be typed.
Check Input Error
The scanf() function will return several items that were successfully read and assigned to variables in the program. This value can be tested to determine if any errors occurred on the input. For example, the call
if (scanf("%s %s %i", str2, str3, &i2) != 3)
print("Error on input.\n");
tests to ensure that scanf() successfully read and assigned three values. If not, an appropriate message is displayed.
scanf() with Field Widths
The scanf() function has two choices for terminating input. For either choice, the string starts at the first non-whitespace character encountered. If you use the %s format, the string runs up to (but not including) the next whitespace character (blank, tab, or newline). If you specify a field width, as in %10s , the scanf() collects up to 10 characters or up to the first whitespace character, whichever comes first.
Input Statement | Qriginal Input Queue | name Contents | Remaining Queue |
scanf("%s", name); | AirSuppply◊Com | AirSupply | ◊Com |
scanf("%5s", name); | AirSuppply◊Com | AirSu | ppply◊Com |
scanf("%5s", name); | 123◊GoGoGo | 123 | ◊GoGoGo |
* the ◊ represents the space character
3.2 Basic Input/Output in C++
In C++, the << and >> are overloaded to perform I/O operations. When used in an expression in which the left operand is a stream, the >> is an input operator, and the << is an output operator.
In the language of C++, the >> is called an extractor because it extracts data from the input stream. The << is called an inserter because it inserts data into the output stream. The general forms of these operators are shown here:
input_stream >> variable;
output_stream << expression;
For example, the following fragment inputs two integer variables:
int i, j;
cin >> i >> j;
The following statement displays "This is a test 10 20":
cout << "This is a test " << 10 << << ' ' << 4 * 5;
I/O Stream and Header Files
The standard C++ iostream library automatically opens the following streams:
Stream | Meaning |
---|---|
cin | Standard input |
cout | Standard output |
cerr | Standard error (output) output |
clog | Standard logging (output) stream (the buffered version of cerr) |
wcin | Wide-character version of cin |
wcout | Wide-character version of cout |
wcerr | Wide-character version of cerr |
wclog | Wide-character version of wclog |
By default, the standard streams are used to communicate with the console. However, in environments that support I/O redirection (such as DOS, UNIX, and Windows), the standard streams can be redirected to other devices or files.
The I/O Headers
The standard C++ I/O system relies upon several headers. They are shown here:
Header | For | Description |
---|---|---|
<fstream> | File I/O | this file declares services for user-controlled file processing. We will discuss this in detail in EE2440-Lesson 09: Standard Sequential Components |
<iomanip> | Parameterized I/O manipulators | This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision. |
<ios> | Basic I/O support | |
<iosfwd> | Forward declarations used by the I/O system | |
<iostream> | General I/O | This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream, and the buffered standard error stream, respectively. |
<istream> | Basic input support | |
<ostream> | Basic output support | |
<sstream> | String-based streams | |
<streambuf> | Low-level I/O support |
Several of these headers are used internally by the I/O system. In general, you program will only include <iostream>, <fstream>, <sstream>, or <iomanip>.
Standard Output Stream (cout)
The predefined object cout is an instance of ostream class. The cout object is said to be "connected to" the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less-than signs as shown in the following example.
cout << "This is a message!"; // prints "This is a message" on screen
cout << 255; // prints number 255 on screen
cout << num; // prints the value of num on screen
The << operator inserts the data that follows it into the stream that precedes it. In the examples above, it inserted the literal string "This is a message!", the number 120, and the value of variable num into the standard output stream cout.
Note that the string must be enclosed in double-quotes ("), and the characters are enclosed in single-quotes ('). If there are no quotation marks, the text is treated as a variable, and its value is printed instead. For example, these two statements have very different results:
cout << "Hello"; // prints "Hello" string on the screen
cout << Hello; // prints the content of variable Hello
Print mix data in a single statement
The C++ compiler also determines the data type of variable to be output and selects the appropriate stream insertion operator to display the value. The << operator is overloaded to output data items of built-in types integer, float, double, strings, and pointer values. The insertion operator << may be used more than once in a single statement, as shown below, and endl is used to add a new-line at the end of the line.
cout << "This " << "is a " << "single C++ statement." << endl;
Chaining insertions is especially useful for mixing literals and variables in a single statement:
int age = 25, zipcode = 90032;
cout << "I am " << age << " years old and my zipcode is " << zipcode << endl;
The output of the previous statement would be:
I am 25 years old and my zipcode is 90032
Print on Next Line
To insert a line break, a new-line character ('\n') shall be inserted at the exact position the line should be broken.
cout << "First sentence.\n";
cout << "Second sentence.\nThird sentence.";
This produces the following output:
First sentence.
Second sentence.
Third sentence.
Alternatively, the endl manipulator can also be used to break lines. For example:
cout << "First sentence." << endl;
cout << "Second sentence." << endl << "Third sentence";
This would print:
First sentence.
Second sentence.
Third sentence.
Standard Input Stream (cin)
The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater-than signs, as shown in the following example.
int age;
cin >> age;
The first statement declares a variable of type int called age, and the second extracts from cin a value to be stored in it. This operation makes the program wait for input from cin; generally, this means that the program will wait for the user to enter some sequence with the keyboard. In this case, note that the characters introduced using the keyboard are only transmitted to the program when the ENTER (or RETURN) key is pressed. Once the statement with the extraction operation on cin is reached, the program will wait for as long as needed until some input is introduced.
The C++ compiler will determine the data type of the entered value and selects the appropriate stream extraction operator to extract the value and store it in the given variables.
The stream extraction operator >> may be used more than once in a single statement. To request more than one datum, you can use the following −
cin >> a >> b;
This will be equivalent to the following two statements −
cin >> a;
cin >> b;
cin and Strings
cin and Strings
The extraction operator can be used on cin to get strings of characters in the same way as with fundamental data types:
string myString;
cin >> myString;
However, cin extraction always considers spaces (whitespaces, tabs, newline...) as terminating the value being extracted, and thus extracting a string means always extract a single word, not a phrase or an entire sentence.
To get an entire line from cin, there exists a function called getline, that takes the stream (cin) as the first argument and the string variable as the second. For example:
// cin with strings #include <iostream> #include <string> using namespace std; int main () { string mystr; cout << "What is your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".\n"; cout << "What is your favorite team? "; getline (cin, mystr); cout << "I like " << mystr << " too!\n"; return 0; }
The results:
What is your name? Ryan Lin
Hello Ryan Lin.
What is your favorite team? The LA Lakers
I like The LA Lakers too!
Standard Error Stream (cerr)
The C++ cerr is the standard error stream that is used to output the errors. This is also an instance of the iostream class. As cerr in C++ is un-buffered, so it is used when one needs to display the error message immediately.
The cerr is also used in conjunction with the stream insertion operator, as shown in the following example.
#include <iostream>
using namespace std;
int main() {
char str[] = "Unable to read....";
cerr << "Error message : " << str << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Error message : Unable to read....
Standard Log Stream (clog)
The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen, but the object clog is buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed.
The clog is also used in conjunction with the stream insertion operator as shown in the following example.
#include <iostream>
using namespace std;
int main() {
char str[] = "Unable to read....";
clog << "Error message : " << str << endl;
}
When the above code is compiled and executed, it produces the following result −
Error message : Unable to read....
The Format Flags
Each stream has associated with ut a set of format flags that control the way information is formatted. The iso_base class declares a bitmask enumeration called fmtflags in which the following values are defined:
adjustfield | basefield | boolalpha | dec |
fixed | floatfield | hex | internal |
left | oct | right | scientific |
showbase | showpoint | showpos | skipws |
unitbuf | uppercase |
These values are used to set or clear the format flags using functions such as setf() and unsetf().
- When the skipws flag is set, leading whitespace characters (space, tabs, and newlines) are discarded when performing input on a stream. When skipws is cleared, whitespace character is not discarded.
- When the left flag is set, the output is left-justified. When right is set, the output is right-justified. When the internal flag is set, a numeric value is padded to fill a field by inserting spaces between any sign or base character. If none of these flags is set, the output is right-justified by default.
- By default, numeric values are output in decimal. However, it is possible to change the number base.
- Setting the oct flag causes output to be displayed in octal.
- Setting the hex flag causes output to be displayed in hexadecimal.
- To return output to decimal, set the dec flag.
- Setting showbase causes the base of numeric values to be shown. For example, if the conversion base is hexadecimal, the value 1F will be displayed as 0x1F.
- By default, when scientific notation is displayed, the e is in lowercase. Also, when a hexadecimal value is displayed, the x is in lowercase. When uppercase is set, these characters are displayed in uppercase.
- Setting showpos causes a leading plus sign to be displayed before positive values.
- Setting showpoint causes a decimal point and trailing zeros to be displayed for all floating-point output — whether needed or not.
- By setting the scientific flag, floating-point numeric values are displayed using scientific notation. When fixed is set, floating-point values are displayed using normal notation. When neither flag is set, the compiler chooses an appropriate method.
- When unitbuf is set, the buffer is flushed after each insertion operation.
- When boolalpha is set, Booleans can be input or output using the keywords true and false.
- Since it is common to refer to the oct, dec, and hex field, they can be collectively referred to as basefield. Similarly, the left, right, and internal fields can be referred to be adjustfield.
- Finally, the scientific and fixed fields can be referenced as floatfield.
The I/O Manipulators
In addition to setting or clearing the format flags directly, you can alter the format parameters of a stream through the use of special functions called manipulators, which can be included in an I/O expression. The standard manipulators are shown in the following table:
Manipulator | Description | Input/Output |
---|---|---|
boolalpha | Turns on boolapha flag | Input/Output |
dec | Read and write decimal values for integer, the same as setbase(10) | Input/Output |
endl | Output a newline character and flush the stream | Output |
ends | Output a null | Output |
fixed | Uses decimal notation for floating-point values | Output |
flush | Flush a stream | Output |
hex | Read and write hexadecimal values for integers, the same as setbase(16) | Input/Output |
internal | Turns on internal flag | Output |
left | Adjusts output to the left | Output |
nobooalpha | Turns off boolalpha flag | Input/Output |
noshownbase | Turns off showbase flag | Output |
noshowpoint | Turns off showpoint flag | Output |
noshowpos | Turns off showpos flag | Output |
noskipws | Turns off skipws flag | Input |
nounitbuf | Turns off unitbuf flag | Output |
nouppercae | Turns off uppercase flag | Output |
oct | Read and write octal values for integer, the same as setbase(8) | Input/Output |
resetioflags(fmtflags f) | Turns off the flags specified in f | Input/Output |
right | Adjusts output to the right | Output |
scientific | Uses scientific floating-point values | Output |
setbase(int base) | Set the number base to base | Input/Output |
setfill(in ch) | Set the fill character to ch | Output |
setiosflags(fmtflags f) | Turn on the flags specified in f | Input/Output |
setprecision(int p) | Set the number of digits of precision | Output |
setw(int w) | Set the field width to w | Output |
showbase | Indicates the numeric base of numeric values | Output |
showpoint | Turns on showpoint flag | Output |
showpos | Shows a positive sign on positive numbers | |
skipws | Turns on skipws flag | Input |
unitbuf | Turns on unitbuf flag | Output |
uppercase | Display uppercase letters for numeric values | Output |
ws | Skip leading whitespace | Input |
To use a manipulator that takes a parameter, you must include <iomanip>.
Formatted the Output Values 01
For example:
#include <iomanip> #include <iostream> using namespace std; int main() { double A = 100; double B = 2001.5251; double C = 201455.2646; // We can use setbase(16) here instead of hex // formatting cout << hex << left << showbase << nouppercase; // actual printed part cout << (long long)A << endl; // We can use dec here instead of setbase(10) // formatting cout << setbase(10) << right << setw(15) << setfill('_') << showpos << fixed << setprecision(2); // actual printed part cout << B << endl; // formatting cout << scientific << uppercase << noshowpos << setprecision(9); // actual printed part cout << C << endl; return 0; }
The results:
0x64
_______+2001.53
2.014552646E+05
Formatted the Output Values 02
#include <iostream> #include <iomanip> using namespace std; int main() { const float tenth = 0.1; const float one = 1.0; const float big = 1234567890.0; cout << "A. " << tenth << ", " << one << ", " << big << endl; cout << "B. " << fixed << tenth << ", " << one << ", " << big << endl; cout << "C. " << scientific << tenth << ", " << one << ", " << big << endl; cout << "D. " << fixed << setprecision(3) << tenth << ", " << one << ", " << big << endl; cout << "E. " << setprecision(20) << tenth << endl; cout << "F. " << setw(8) << setfill('*') << 34 << 45 << endl; cout << "G. " << setw(8) << 34 << setw(8) << 45 << endl; return 0; }
The result:
A. 0.1, 1, 1.23457e+09
B. 0.100000, 1.000000, 1234567936.000000
C. 1.000000e-01, 1.000000e+00, 1.234568e+09
D. 0.100, 1.000, 1234567936.000
E. 0.10000000149011611938
F. ******3445
G. ******34******45
Boolean Notations
One of the most interesting format flags in the modern iostream library is boolalpha. This flag can be set either directly or by using the manipulators boolalpha() or noboolalpha(). What makes boolalpha so interesting is that setting it allows you to input and output Boolean values using the keywords true and false. Normally, you must enter 1 for true and zero for false. For example, consider the following program:
// Demonstrate boolalpha format flag #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; int main() { bool b; cout << "Before setting boolalpha flag: "; b = true; cout << b << " "; b = false; cout << b << endl; cout << "After setting boolalpha flag: "; b = true; cout << boolalpha << b << " "; b = false; cout << b << endl; cout << "Enter a Boolean value: "; cin >> boolalpha >> b; cout << "You entered " << b; system("pause"); // for C++Builder return 0; }
Here is a sample run:
Before setting boolalpha flag: 1 0
After setting boolalpha flag: true false
Enter a Boolean value: false
You entered false
Once the boolalpha flag has been set, Boolean values are input and output using the word true and false. As the program shows, you must set the boolalpha flag for cin and cout separately. Like all format flags, setting boolalpha for one stream does not imply that it is also set for another.
You would not be able to see any difference in cout, cerr, and clog with these small examples, but while writing and executing big programs the difference becomes obvious. So it is good practice to display error messages using cerr stream and while displaying other log messages then clog should be used.
Questions
- Write a program that does the following:
- Create two variables, num and denom, that represent a fraction's numerator (top) and denominator (bottom).
- Ask the user to supply values for the numerator and denominator.
- Puts the values supplied into the variables
- Displays the fraction in the format 2/3, with a slash between the two numbers.
Some sample interactions with this program might look like below:
Enter the numerator: 4
Enter the denominator: 7
Fraction = 4/7 - Let me think about it ...