MODULE 18: THE C++ FORMATTED I/O PROGRAMMING
| My Training Period: xx hours
This is a continuation from the previous Module. The source code for this Module is available at C Formatted I/O source codes. The lab worksheets for your practice are:main() and printf(), scanf()/scanf_s().
C abilities that supposed to be acquired: Appreciates other printf() and scanf() family.
5.11 Formatting Input With scanf()
scanf (format-control-string, other-arguments);
scanf("%e%f%g",&a, &b, &c);
|
Conversion specifier | Description |
Integers |
|
d | Read an optionally signed decimal integer. The corresponding argument is a pointer to integer. |
i | Read an optionally signed decimal, octal, or hexadecimal integer. The corresponding argument is a pointer to integer. |
o | Read an octal integer. The corresponding argument is a pointer to unsigned integer. |
u | Read an unsigned decimal integer. The corresponding argument is a pointer to unsigned integer. |
x or X | Read a hexadecimal integer. The corresponding argument is a pointer to unsigned integer. |
h or l | Place before any of the integer conversion specifiers to indicate that a short or long integer is to be input. |
Floating-point numbers |
|
e, E,f, g or G | Read a floating-point value. The corresponding argument is a pointer to a floating-point variable |
l or L | Place before any of the floating-point conversion specifiers to indicate that a double or long double value is to be input. |
Characters and strings |
|
c | Read a character. The corresponding argument is a pointer to char, no null (‘\0’) is added. |
s | Read a string. The corresponding argument is a pointer to an array of type char that is large enough to hold the string and a terminating null (‘\0’) character. |
Scan set [scan characters] | Scan a string for a set of characters that are stored in an array. |
Miscellaneous |
|
p | Read a pointer address of the same form produced when an address is output with %p in a printf() statement. |
n | Store the number of characters input so far in this scanf(). The corresponding argument is a pointer to integer. |
% | Skip a percent sign (%) in the input. |
Table 5.7: Conversion specifiers for scanf() | |
Let explore through program examples:
// reading integers
#include <stdio.h>
int main()
{
int a, b, c, d, e, f, g;
printf("Reading integers from standard input\n");
printf("------------------------------------\n\n");
printf("Enter seven integers separated by space: ");
scanf("%d%i%i%i%o%u%x", &a, &b, &c, &d, &e, &f, &g);
printf("The input displayed as decimal integers is: \n");
printf("%d %d %d %d %d %d %d\n", a, b, c, d, e, f, g);
return 0;
}

More program example:
// reading floating-point numbers
#include <stdio.h>
int main()
{
float a, b, c;
printf(" Reading floating-point numbers\n");
printf("Compare the output with the source code.\n");
printf("----------------------------------------\n\n");
printf("Enter three floating-point numbers, separated by space: \n");
scanf("%e%f%g", &a, &b, &c);
printf("Here are the numbers entered in plain\n");
printf("floating-point notation:\n");
printf("%f %f %f\n", a, b, c);
return 0;
}

Another program example:
// reading characters and strings
#include <stdio.h>
int main()
{
char x, y[20];
printf("Enter a string: ");
scanf("%c%s", &x, y);
printf("The input was: \n");
printf("the character \"%c\" ", x);
printf("and the string \"%s\"\n", y);
return 0;
}
-----------------------------------------------------------

Program example again:
// input data with a field width
#include <stdio.h>
int main()
{
int x, y;
printf("Enter a six digit integer: ");
scanf("%2d%d", &x, &y);
printf("The integers input were %d and %d\n", x, y);
return 0;
}

Well, more program example:
// reading and discarding characters from the input stream
#include <stdio.h>
int main()
{
int month1, day1, year1, month2, day2, year2;
printf("Enter a date in the form mm-dd-yy: ");
// pad 0 for two fields and discarding the - characters....
scanf("%d%*c%d%*c%d", &month1, &day1, &year1);
printf("month = %02d day = %02d year = %02d\n\n", month1, day1, year1);
printf("Enter a date in the form mm/dd/yy: ");
// pad 0 for two fields and discarding the / characters...
scanf("%d%*c%d%*c%d", &month2, &day2, &year2);
printf("month = %02d day = %02d year = %02d\n", month2, day2, year2);
return 0;
}
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.
Function | Description & Prototype |
scanf() | Read from the standard input streamstdin. Includethe stdio.h. |
| int scanf(const char *restrict |
fscanf() | Read from the named input stream. Include the stdio.h. |
| int fscanf(FILE *restrict |
sscanf() | Read from the string s. Include the stdio.h. |
| int sscanf(const char *restrict |
vscanf() | Equivalent to the scanf() function except that instead of being called with a variable number of arguments, they are called with an argument list as defined in the stdarg.h. Include the stdarg.h andstdio.h. |
| int vscanf(const char *restrict |
vsscanf() | Equivalent to the sscanf() functions except that instead of being called with a variable number of arguments, they are called with an argument list as defined in the stdarg.h. Include the stdarg.h andstdio.h. |
| int vsscanf(const char *restrict |
vfscanf() | Equivalent to the fscanf() function except that instead of being called with a variable number of arguments, they are called with an argument list as defined in the stdarg.h. Include the stdarg.h andstdio.h. |
| int vfscanf(FILE *restrict |
Table 5.8: scanf() family | |
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) atPacketStorm Security Portal regarding the buffer overflow.
C++ provides an alternative to printf() and scanf() function calls for handling input/output of the standard data types and strings. For example:
printf("Enter new tag: ");
scanf("%d", &tag);
printf("The new tag is: %d\n", tag);
Is written in C++ as:
cout<<"Enter new tag: ";
cin>>tag;
cout<<"The new tag is: "<<tag<<’\n’;
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 streamcout.
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:
Get a value for tag from the input stream cin.
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/output.
iostream library provide hundreds of IO 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.
// concatenating the << operator
#include <iostream>
using namespace std;
int main()
{
cout<<"47 plus 54 is "<<(47 + 54)<<endl;
cout<<"Welcome to C++ stream\n";
return 0;
}

// printing the address stored in a char * variable
#include <iostream>
using namespace std;
int main()
{
char * string = "pointer testing";
cout<<"\nThe string is: "<<string
<<"\nValue of (void *) string, the address is: "
<<(void *)string <<endl;
return 0;
}

// stream extraction operator, input from keyboard with cin
#include <iostream>
using namespace std;
int main()
{
int x, y;
cout<<"Enter two integers: ";
cin>>x>>y;
cout<<"Sum of "<<x<<" and "<<y<<" is "<<(x + y)<<endl;
return 0;
}

// stream extraction operator, a variation of cin
#include <iostream>
using namespace std;
int main()
{
int x, y;
cout<<"Enter two integers: ";
cin>>x>>y;
cout<<x<<(x == y?" is " : " is not ")<<"equal to "<<y<<endl;
return 0;
}

// stream extraction operator, another variation of cin
#include <iostream>
using namespace std;
int main()
{
int mark, HighMark = -1;
cout<<"Enter grade(eof -Ctrl+Z- to stop): ";
while(cin>>mark)
{
if(mark>HighMark)
HighMark = mark;
cout<<"Enter grade(eof -Ctrl+Z- to stop): ";
}
cout<<"\nHighest grade is: "<<HighMark<<endl;
return 0;
}

// a simple stream input/output
#include <iostream>
using namespace std;
int main()
{
cout<<"Enter your age: ";
int myAge;
cin>>myAge;
cout<<"Enter your friend's age: ";
int friendAge;
cin>>friendAge;
if(myAge > friendAge)
cout<<"You are older.\n";
else if(myAge < friendAge)
cout<<"You are younger.\n";
else
cout<<"You and your friend are the same age.\n";
return 0;
}

Usage of the '\n', endl withcout example.
// some of the cout usage
#include <iostream>
using namespace std;
void main(void)
{
int q, s = 0, t = 0;
q = 10*(s + t);
// using the " for breaking literal strings
cout<<"Enter 2 integer numbers,"
" separated by space: ";
cin>>s>>t;
q = 10*(s + t);
// using '\n' for newline
cout<<"simple mathematics calculation, just for demo"<<'\n';
// using endl for new line
cout<<"q = 10(s + t) = "<<q<<endl;
cout<<"That all folks!!"<<"\n";
cout<<"Study the source code and the output\n";
}

cout and cin example for function call and array.
// cout and cin example for function call and array
#include <iostream>
using namespace std;
float simple_calc(float);
void main(void)
{
float x = 3, y[4], sum=0;
int i;
// cout with function call
cout<<"Square of 3 is: "<<simple_calc(x)<<'\n';
cout<<"Study the source code and the output"<<endl;
for (i=1; i<5; i++)
{
cout<<"Enter arrays' data #"<<i<<" : ";
cin>>y[i];
// an array
sum = sum + y[i];
}
cout<<"Sum of the arrays' data is: "<<sum<<endl;
cout<<"Press Enter key to quit\n";
}
float simple_calc(float x)
{
float p;
p = (x * x);
return p;
}

Other I/O header files include:
Header file | Description |
iomanip.h/iomanip | Used for performing formatted IO with so-called parameterized stream manipulators. |
strstream.h/strstream | Used for performing in-memory formatting. This resembles file processing IO operation, normally performed to and from character arrays rather than files. |
stdiostream.h/stdiostream | Used for programs that mix the C and C++ style of IO. This can be used for modifying existing C program or migrating C to C++. |
Table 5.9: Other header files used for C++ formatted I/O | |
// printing floating-point numbers with floating-point conversion specifiers
#include <cstdio>
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);
}

Then, program example compiled usinggcc on FeDora 3.
[bodo@bakawali ~]$ cat module5.c
/* Using the p, n, and % conversion specifiers */
/* ****************module5.c****************** */
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* pointer variable */
int *ptr;
int x = 12345, y;
/* assigning address of variable x to variable ptr */
ptr = &x;
printf("\nUsing the p, n, and %% conversion specifiers.\n");
printf("Compare the output with the source code\n");
printf("-----------------------------------------------\n\n");
printf("The value of pointer ptr is %p\n", ptr);
printf("The address of variable x is %p\n\n", &x);
printf("Total characters printed on this line is:%n", &y);
printf(" %d\n\n", y);
y = printf("This line has 28 characters\n");
printf("%d characters were printed\n\n", y);
printf("Printing a %% in a format control string\n");
return 0;
}
[bodo@bakawali ~]$ gcc module5.c -o module5
[bodo@bakawali ~]$ ./module5
Using the p, n, and % conversion specifiers.
Compare the output with the source code
-----------------------------------------------
The value of pointer ptr is 0xbff73840
The address of variable x is 0xbff73840
Total characters printed on this line is: 41
This line has 28 characters
28 characters were printed
Printing a % in a format control string
[bodo@bakawali ~]$
Quite a complete discussion for other C++ formatted I/O will be discussed inC++ Formatted Input/Output.