|< C Formatted I/O 1 | Main | C & C++ Program Controls 1 >| Site Index | Download |


 

 

 

 

MODULE 5a

  MORE ON C FORMATTED  I/O PROGRAMMING 2

---------------------------------------------------------------

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()

  • Used for precise input formatting.

  • Every scanf() function contains a format control string that describes the format of the data to be input.

  • The format control string consists of conversion specifications and literal characters.

  • Function scanf() has the following input formatting capabilities

  1. Inputting all types of data.

  2. Inputting specific characters from an input stream.

  3. Skipping specific characters in the input stream.

  • It is written in the following form:

scanf (format-control-string, other-arguments);

  • For example:

scanf("%e%f%g", &a, &b, &c);

  • 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.

 

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()

// 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;

}

 

Output:

 

C formatted I/O read integer

// 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;

 }

 

Output:

 

C formatted I/O read float number

 

 // 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;

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

-----------------------------------------------------------

C formatted I/O read character and string

            // 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;

}

 

Output:

 

C formatted I/O input data with field

// 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:

 

C formatted I/O reads input stream

Function

Description & Prototype

scanf()

Read from the standard input stream stdin.  Include the stdio.h.

 

int scanf(const char *restrict format, ... );

fscanf()

Read from the named input stream.  Include the stdio.h.

 

int fscanf(FILE *restrict stream, const char *restrict format, ... );

sscanf()

Read from the string s.  Include the stdio.h.

 

int sscanf(const char *restrict s, const char *restrict format, ... );

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 and stdio.h.

 

int vscanf(const char *restrict format, va_list arg);

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 and stdio.h.

 

int vsscanf(const char *restrict s, const char *restrict format, va_list arg);

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 and stdio.h.

 

int vfscanf(FILE *restrict stream, const char *restrict format, va_list arg);

 

Table 5.8:  scanf() family

 

 

5.12    An Introduction To C++ Input/Output Streams

printf("Enter new tag:  ");

scanf("%d", &tag);

printf("The new tag is: %d\n", tag);

cout<<"Enter new tag: ";

cin>>tag;

cout<<"The new tag is: "<<tag<<’\n’;

The string “Enter new tag” is put to the output stream cout.

Get a value for tag from the input stream cin.

// 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;

}

 

Output:

 

C formatted I/O concat operator

 

// 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;

}

 

Output:

 

C formatted I/O pointer to address

 

// 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;

}

 

Output:

 

C formatted I/O stream extraction operator

 

// 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;

}

 

Output:

 

C formatted I/O stream extraction operator

 

// 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;

}

 

Output:

 

C formatted I/O stream extraction operator

 

// 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;

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

C formatted I/O stream

// 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";

}

 

Output:

 

C formatted I/O endl

// 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;

}

 

Output:

 

C formatted I/O array

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);

}

 

Output:

 

C formatted I/O

 

[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 ~]$

 

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Further C & C++ reading and digging:

 

  1. Check the best selling C/C++ books at Amazon.com.
  1. The formatted I/O for wide character/Unicode is discussed Locale, Unicode & Wide Characters and the example of the implementation (Microsoft C) is presented Win32 Users and Groups Manipulations.

 

 

 

 

 

 

 

 

|< C Formatted I/O 1 | Main | C & C++ Program Controls 1 >| Site Index | Download |


C Formatted Input/Output:  Part 1 | Part 2 |