C Programming Module5 Tenouk
C Programming Module5 Tenouk
C FORMATTED INPUT/OUTPUT
-----------------------------------------------------
MODULE 18
C++ FORMATTED I/O
Abilities
5.1 Introduction
- This Module deals with the formatting features of printf(), scanf(), cin and cout, the most
frequently use functions.
- Here, you will learn how to use the predefined functions provided by the header files (standard or non
standard).
- printf() function input data from the standard input stream.
- scanf(), output data to the standard output stream.
- For other functions that use the standard input and standard output are gets(), puts(),
getchar() and putchar(). Keep in mind that some of the functions discussed here are non-
standard.
- We have to include header file stdio.h (C) or iostream.h/iostream (C++) in program to call
these functions.
5.2 Streams
- For precise output formatting, every printf() call contains a format control string that describes the
output format.
- The format control string consists of:
1. Conversion specifiers.
2. Flags.
3. Field widths.
4. Precisions.
5. Literal characters.
- Together with percent sign (%), these, form conversion specifications. Function printf() can
perform the following formatting capabilities:
www.tenouk.com Page 1 of 20
- As discussed in Module 4, printf() is a variadic function. It can accept variable number of
arguments. The printf() general form is:
- For example:
- The format-control-string describes the output format, and other-arguments (optional) correspond to
each conversion specification in the format-control-string.
- Each conversion specification begins with a percent sign (%) and ends with a conversion specifier.
- Integer is a whole number, such as 880 or –456, that contains no decimal point.
- Table 5.1 is a summary of an integer conversion specifier.
Conversion
Description
specifier
d Display a signed decimal integer
Display a signed decimal integer. (Note: The i and d specifiers are different
i
when used with scanf().)
o Display an unsigned octal integer.
u Display an unsigned decimal integer.
Display an unsigned decimal integer. x causes the digit 0-9 and the letters A-F
x or X
to be displayed, and x causes the digits 0-9 and a–f to be displayed.
Place before any integer conversion specifier to indicate that a short or long
h or l (letter l)
integer is displayed respectively.
int main()
{
printf("Various format for integer printing\n");
printf("-------------------------------------\n");
printf("%d\n", 455);
printf("%i\n", 455); //i same as d in printf()
printf("%d\n", +455);
printf("%d\n", -455);
printf("%hd\n", 32000);
printf("%ld\n", 2000000000L);
printf("%o\n", 455);
printf("%u\n", 455);
printf("%u\n", -455);
//-455 is read by %u and converted to the unsigned
//value 4294966841 by 4 bytes integer
printf("%x\n", 455);
printf("%X\n", 455);
system("pause");
return 0;
}
Output:
www.tenouk.com Page 2 of 20
5.5 Printing Floating-point Number
- Exponential notation is the computer equivalent of scientific notation used in mathematics. For
example, 150.2352 is represented in scientific notation as:
1.502352 x 102
1.502352E+02 by computer
#include <stdio.h>
#include <stdlib.h>
void main()
{
printf("Printing floating-point numbers with\n");
printf("floating-point conversion specifiers.\n");
printf("Compare the output with source code\n\n");
printf("1. %e\n", 1234567.89);
printf("2. %e\n", +1234567.89);
printf("3. %e\n", -1234567.89);
printf("4. %E\n", 1234567.89);
printf("5. %f\n", 1234567.89);
printf("6. %g\n", 1234567.89);
printf("7. %G\n", 1234567.89);
system("pause");
}
Output:
www.tenouk.com Page 3 of 20
5.6 Printing Strings And Characters
- c and s conversion specifiers are used to print individual characters and strings respectively.
- Conversion specifier c requires a char argument and s requires a pointer to char as an argument.
- s causes characters to be printed until a terminating NULL (‘\0’) character is encountered.
- A program example.
int main()
{
char character = 'A';
char string[] = "This is a string";
char *stringPtr = "This is also a string";
printf("---------------------------------\n");
printf("---Character and String format---\n");
printf("---------------------------------\n\n");
printf("%c <--This one is character\n", character);
printf("\nLateral string\n");
printf("%s\n", "This is a string");
printf("\nUsing array name, the pointer to the first array's element\n");
printf("%s\n", string);
printf("\nUsing pointer, pointing to the first character of string\n");
printf("%s\n", stringPtr);
system("pause");
return 0;
}
Output:
www.tenouk.com Page 4 of 20
Conversion specifier Description
Display a pointer value (memory address) in an implementation
p
defined manner.
Store the number of characters already output in the current
n printf() statement. A pointer to an integer is supplied as the
corresponding argument. Nothing is displayed.
% Display the percent character.
int main()
{
int *ptr;
//pointer variable
int x = 12345, y;
ptr = &x;
Output:
- A field width determines the exact size of a field in which data is printed.
- If the field width is larger then the data being printed, the data will normally be right-justified within
that field.
- An integer representing the field width is inserted between the percent sign (%) and the conversion
specifier in the conversion specification.
- Function printf() also provides the ability to specify the precision with which data is printed.
- Precision has different meanings for different data types.
- A program example.
www.tenouk.com Page 5 of 20
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf(" Printing integers right-justified.\n");
printf("Compare the output with the source code\n");
printf("---------------------------------------\n\n");
printf("%4d\n", 1);
printf("%4d\n", 12);
printf("%4d\n", 123);
printf("%4d\n", 1234);
printf("%4d\n\n", 12345);
printf("%4d\n", -1);
printf("%4d\n", -12);
printf("%4d\n", -123);
printf("%4d\n", -1234);
printf("%4d\n", -12345);
system("pause");
return 0;
}
Output:
- Another example:
int main()
{
int i = 873;
float f = 123.94536;
char s[] = "Happy Birthday";
Output:
www.tenouk.com Page 6 of 20
- By using asterisk (*), it is also can be like this:
printf("%*.*f", 7, 2, 98.736)
- This statement uses 7 for the field width, 2 for the precision and will output the value 98.74 right-
justified.
Flag Description
- (minus sign) Left-justify the output within the specified field
Display a plus sign preceding positive values and a minus sign preceding
+ (plus sign)
negative values.
space Print a space before a positive value not printed with the + flag.
Prefix 0 to the output value when used with the octal conversion specifier o.
Prefix 0x or 0X to the output value when used with the hexadecimal
conversion specifiers x or X. Force a decimal points for a floating-point
#
number printed with e, E, f, g, or G that does not contain a fractional part.
(Normally the decimal point is only printed if a digit follows it). For g and G
specifiers, trailing zeros are not eliminated.
0 (zero) Pad a field with leading zeros.
int main()
{
printf("Right justifying and left justifying values.\n");
printf(" Compare the output with the source code.\n");
printf("--------------------------------------------\n\n");
printf("%10s%10d%10c%10f\n\n", "hello", 7, 'a', 1.23);
printf("%-10s%-10d%-10c%-10f\n", "hello", 7, 'a', 1.23);
system("pause");
return 0;
}
Output:
www.tenouk.com Page 7 of 20
- Program example:
int main()
{
printf("Printing numbers with and without the + flag.\n");
printf(" Compare the output with the source code\n");
printf("---------------------------------------------\n\n");
printf("%d\n%d\n", 786, -786);
printf("%+d\n%+d\n", 786, -786);
system("pause");
return 0;
}
Output:
- Another example:
int main()
{
printf("Printing a space before signed values\n");
printf(" not preceded by + or -n\n");
printf("--------------------------------------\n\n");
printf("% d\n% d\n", 877, -877);
system("pause");
return 0;
}
Output:
www.tenouk.com Page 8 of 20
- Program example:
int main()
{
int c = 1427;
float p = 1427.0;
Output:
- Program example.
int main()
{
printf("Printing with the 0 (zero) flag fills in leading zeros\n");
printf(" Compare the output with the source code\n");
printf("-------------------------------------------------------\n\n");
printf("%+09d\n", 762);
printf("%09d", 762);
printf("\n");
system("pause");
return 0;
}
Output:
www.tenouk.com Page 9 of 20
1.4 Printing Literals And Escape Sequences
- Various control characters, such as newline and tab, must be represented by escape sequences.
- An escape sequence is represented by a backslash (\) followed by a particular escape character.
- Table 5.5 summarizes all the escape sequences and the actions they cause.
- Other printf() family that you might find somewhere, sometime is listed in the following Table. It
is important to note that some of these are not part of the standard library but are widely available. You
have to check your compiler.
www.tenouk.com Page 10 of 20
int vprintf(const char *restrict format, va_list ap);
Prints to a string from a va_arg structure. Equivalent to sprintf() respectively,
except that instead of being called with a variable number of arguments, they are
vsprintf()
called with an argument list as defined by stdarg.h. Include stdarg.h and
stdio.h.
int vsprintf(char *restrict s, const char *restrict format, va_list ap);
Prints to a string with length checking from a va_arg structure. Equivalent to
snprintf(), except that instead of being called with a variable number of
vsnprintf()
arguments, they are called with an argument list as defined by stdarg.h. Include
stdarg.h and stdio.h.
int vsnprintf(char *restrict s, size_t n, const char *restrict format, va_list ap);
- For example:
- The format-control-string describes the formats of the input, and the other-arguments are pointers to
variables in which the input will be stored.
- Table 5.7 summarizes the conversion specifiers used to input all types of data.
www.tenouk.com Page 11 of 20
Scan set [scan characters] Scan a string for a set of characters that are stored in an array.
Miscellaneous
Read a pointer address of the same form produced when an address is
p
output with %p in a printf() statement.
Store the number of characters input so far in this scanf(). The
n
corresponding argument is a pointer to integer.
% Skip a percent sign (%) in the input.
//Reading integers
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b, c, d, e, f, g;
Output:
- Program example:
int main()
{
float a, b, c;
Output:
www.tenouk.com Page 12 of 20
- Program example:
int main()
{
char x, y[20];
Output:
- Program example:
int main()
{
int x, y;
Output:
- Program example:
//Reading and discarding characters from the input stream
www.tenouk.com Page 13 of 20
#include <stdio.h>
#include <stdlib.h>
int main()
{
int month1, day1, year1, month2, day2, year2;
Output:
- Other scanf() family that you might find is listed in the following Table. It is important to note that
some of these are not part of the standard library but are widely available. You have to check your
compiler.
- Be careful when using the printf() and scanf() families because improper use can generate
buffer overflow problems. The buffer overflows phenomenon widely exploited by malicious, worm
and virus codes. See everyday security updates and the Proof Of Concept (POC) at frsirt regarding the
buffer overflow.
www.tenouk.com Page 14 of 20
- C++ provides an alternative to printf() and scanf() function calls for handling input/output of
the standard data types and strings. For example:
- The first statement uses the standard output stream cout and the operator << (the stream insertion
operator, synonym to “put to”). The statement is read:
The string “Enter new tag” is put to the output stream cout.
- The second statement uses the standard input stream cin and the operator >> (the stream extraction
operator, synonym to “get from”). This statement is read something like:
- The stream insertion and extraction operators, unlike printf() and scanf(), do not require format
strings and conversion specifiers to indicate the data types being output or input.
- The operator & also not required as in scanf(). Mostly done automatically and you have to know
how to use left shift, << and right shift, >> operators together with spaces and new line to do the
formatting. As a conclusion, cout and cin are simpler and easier to use.
- You have to include the iostream.h header file to use these stream input/outputs.
- iostream library provide hundreds of I/O capabilities. The iostream.h contains cin, cout,
cerr (unbuffered standard error device) and clog (buffered standard error device) objects for
standard input stream, standard output stream and standard error stream respectively.
- Let try a simple program example.
int main()
{
cout<<"47 plus 54 is "<<(47 + 54)<<endl;
cout<<"Welcome to C++ stream\n";
system("pause");
return 0;
}
Output:
int main()
{
char * string = "pointer testing";
www.tenouk.com Page 15 of 20
}
Output:
int main()
{
int x, y;
Output:
int main()
{
int x, y;
Output:
int main()
{
int mark, HighMark = -1;
www.tenouk.com Page 16 of 20
while(cin>>mark)
{
if(mark>HighMark)
HighMark = mark;
cout<<"Enter grade(eof -Ctrl+Z- to stop): ";
}
cout<<"\nHighest grade is: "<<HighMark<<endl;
system("pause");
return 0;
}
Output:
int main()
{
cout<<"Enter your age: ";
int myAge;
cin>>myAge;
cout<<"Enter your friend's age: ";
int friendAge;
cin>>friendAge;
Output:
void main(void)
{
int q, s = 0, t = 0;
q = 10*(s + t);
www.tenouk.com Page 17 of 20
cout<<"Enter 2 integer numbers,"
" separated by space: ";
//using the " for breaking literal strings
cin>>s>>t;
q = 10*(s + t);
cout<<"simple mathematics calculation, just for demo"<<'\n';
//using '\n' for newline
cout<<"q = 10(s + t) = "<<q<<endl;
//using endl for new line
cout<<"That all folks!!"<<"\n";
cout<<"Study the source code and the output\n";
system("pause");
}
Output:
float simple_calc(float);
void main(void)
{
float x = 3, y[4], sum=0;
int i;
float simple_calc(float x)
{
float p;
p = (x * x);
return p;
}
Output:
www.tenouk.com Page 18 of 20
- Other I/O header files include:
Table 5.9: Other header files used for C++ formatted I/O
void main()
{
printf("Printing floating-point numbers with\n");
printf("floating-point conversion specifiers.\n");
printf("Compare the output with source code\n\n");
printf("1. %e\n", 1234567.89);
printf("2. %e\n", +1234567.89);
printf("3. %e\n", -1234567.89);
printf("4. %E\n", 1234567.89);
printf("5. %f\n", 1234567.89);
printf("6. %g\n", 1234567.89);
printf("7. %G\n", 1234567.89);
}
Output:
www.tenouk.com Page 19 of 20
int main()
{
int *ptr;
/*pointer variable*/
int x = 12345, y;
ptr = &x;
- Quite a complete discussion for other C++ formatted I/O will be discussed in Module 18.
---------------------------------------------------------o0o ----------------------------------------------------------
www.tenouk.com Page 20 of 20