Printf and Scanf
Printf and Scanf
-----------------------------------------------
C++ FORMATTED
I/O
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.
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:
- 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.
Printing Integers
- 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
Descriptio
specifier
n
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:
- 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:
- 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:
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.
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:
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 Descriptio
- (minus sign) n field
Left-justify the output within the specified
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:
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:
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:
- 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.
- 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.
//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:
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
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.
- 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";
Output:
int main()
{
int x, y;
Output:
int main()
{
int x, y;
Output:
int main()
{
int mark, HighMark = -1;
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);
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:
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:
ptr = &x;