Monday, December 21, 2015

Chapter 4 - Input Output Streams in CPP

                               

LET’S LEARN
INTRODUCTION
STANDARD OUTPUT STREAM: cout
STANDARD INPUT STREAM: cin
C++ MANIPULATORS
    1. endl
    2. setbase()
    3. setw()
    4. setfill()
    5. setprecision()
CHARACTER ENCODING: ASCII AND UNICODE
ASCII
UNICODE
BACKSLASH CHARACTERS
CHAPTER EVALUATION EXERCISE

INTRODUCTION


C++ uses streams (data flow) to perform input and output operations in sequential media such as the screen or the keyboard. A stream is an object where a program can either insert or extract characters to/from it. The standard C++ library includes the header file iostream.h where the standard input and output stream objects are declared.


STANDARD OUTPUT STREAM: "cout"


By default, the standard output device of a C++ program is the monitor/display-screen. The cout statement makes it possible to write data/contents from computers storage units onto the display screen. cout is the C++ stream object for accessing  output related functional features. cout is used along with << called the insertion operator. The << operator inserts data from RHS into the stream on LHS and can be used more than once in a single statement. Look at the following statements:

cout << “Good Morning”; // prints Good Morning on screen

cout << 120;               // prints number 120 on screen

cout << x;                  // prints value of x on screen

cout<< “x”;               // prints character x on screen

cout << “Hello, I am “ << age << “ years old and my pincode is “ << pincode;

In the last statement, if age=24 and pincode=691301 then output is:


Hello, I am 24 years old and my pincode is 691301

 


Inserting a Newline

In C++, a new line can be inserted in 2 ways:

(a)   \n (newline character)             (b)  endl (manipulator)

\n can be streamed with cout in single or double quotes : ‘\n’ or “\n”. Major difference between \n and endl is that, \n is a character and occupies 1 or 2 Byte space, while endl is a manipulator that doesn’t occupy any space.

Note: ‘\n’ is a single character occupying 1 Byte, while “\n” is an array with 2 values ‘\n’, ‘\0’ and hence occupies 2 Bytes. \0 (\zero) signifies null character (end-of-array).

Take a look at the following example statements:
cout << "First Line.\n ";
cout << "Second Line.”<<endl<<”Third Line.”;

// On some compilers, endl will not work with the "std::cout" scope resolution. In such cases, declare "using namespace std" before main() and then use the cout object.

Output

First Line.
Second Line.
Third Line.




STANDARD INPUT STREAM: "cin"

The standard input device is usually the keyboard. Input from the keyboard is stored onto memory location using >> or extraction operator along with the cin stream. For example:

int age;
cin >> age;

The first statement declares a variable of type int called age, and the second one waits for an input from cin (the keyboard) in order to store it in this integer variable. Here, an input value from the keyboard is inserted into the variable named age. So the data flow is from the LHS to RHS. cin>> processes input from the keyboard after RETURN (ENTER) key is pressed.

You can also use cin to request multiple data input of similar or different data types. For example the statement,
    cin >> a >> b;
is the same as,
    cin >> a;
    cin >> b;
where a and b can both be integers, or a can be an integer and b can be float ... and so on.

PROGRAM 14: Write a program to find the area of a circle.


#include<iostream>
#define Pi 3.14   //symbolic constant
int main()
{

  float area, R;

  std::cout<<"Enter radius of circle : ";
  std::cin>>R;

  area=Pi*R*R;

  std::cout<<"Area of circle = "<<area<<" sq.units";

}

Output

 Enter radius of circle  : 5
 Area of circle  =  78.5 sq.units

    

C++ MANIPULATORS

Manipulators are special stream functions that change the input/output format. Manipulators are used along with insertion (<<) and extraction (>>) operators and are defined in the header file iomanip

1.  endl is an output manipulator, that is used to generate a carriage return (Enter key or new line character).

2. setbase() is an output manipulator, that is used to set the base value of a number to octal, hexadecimal or decimal. Base argument 16 (hex) converts decimal/octal number to hexadecimal number. Base argument 8 (oct) converts decimal/hexadecimal number to octal format. Base argument 10 (dec) converts octal/hexadecimal number to decimal format.

PROGRAM 15:Accept a number and display its Octal and Hexadecimal values using manipulator functions: setbase() and oct/hex/dec.

#include<iostream>
#include<iomanip>
using namespace std;

main()
{

  int a;

  // using setbase()
  cout<< "Enter a Number: "; cin>>a;
  cout<< "OCTAL value of "<<a<< " is "<<setbase(8)<<a<<endl;
  cout<< "HEXADECIMAL value of "<<setbase(10)<<a<<" is "<<setbase(16)<<a;

  // using oct, hex, dec manipulator functions
  cout<< "\n\nEnter Another Number: "; cin>>a;
  cout<< "OCTAL value of "<<dec<<a<< " is "<<oct<<a<<endl; //why "dec" ?
  cout<< "HEXADECIMAL value of "<<dec<<a<<" is "<<hex<<a;

}

Output












3.  setw() also called setwidth, is an output manipulator that is used to set the width (number of columns) of a data output. Result would be right aligned. Eg: setw(5)<<a; would reserve 5 positions for the value of variable “a” and place it right aligned.

4.  setfill() is an output manipulator that is used to specify a character which will fill the unused columns within a setw() specified width.


Eg: setfill (‘*’)<<setw(5)<<a; would fill the unused columns with * character. If a=31, result will be ***31.

5.  setprecision() is an output manipulator that is used to control the number of digits a floating point number will display including the integer and fractional part. If precision is to be set only for fractional part, use the fixed-point notation. The fractional part will be rounded up to nearest value where necessary.

Eg.1: cout<<setprecision(3)<<1.579; will assign 3 columns for entire number and print 1.58 (rounded up value).

Eg.2: cout<<fixed<<setprecision(3)<<1.579; will assign 3 columns for fractional part and print 1.579 (exact value).

Eg.3: cout<<fixed<<setprecision(3)<<1.5799; will assign 3 columns for fractional part and print 1.580 (rounded up value).

PROGRAM 16: Apply setw(), setfill() and setprecision() to demonstrate its usage.


#include<iostream>
#include<iomanip>
using namespace std;

main()


  int a = 28;

  // set * as fill value for width=5,10
  cout <<setfill('*')<<setw(5)<<a<<endl;
  cout <<setw(10)<<a<<endl;
 
  // assign 6 digit float
  float b = 9.59281;
 
  // set 2 positions for output
  cout <<endl<<b<<" with Precision 2 = ";
  cout <<setprecision(2)<<b<<endl;
  // now, b = 9.6 (rounded value)
 
  // bring back b to original value, setprecision = 6 digits
  // set FIXED precision to b and print
  cout <<setprecision(6)<<b<<" with FIXED Precision 2 = ";
  cout <<fixed<<setprecision(2)<<b<<endl;
  // now you have set precision value for 2 fractional part
  // so now, b = 9.59 (exact value as declared)

}

Output












#include <bits/stdc++.h>

This is a special header file that includes all header files. You don’t need to remember and declare each header file for each purpose. However, namespace if any has to be declared. For example, from the above program,

#include<iostream>

#include<iomanip>

using namespace std;

  can all be replaced with,

         #include <bits/stdc++.h>

 using namespace std;





CHARACTER ENCODING: ASCII AND UNICODE

As you have learned earlier, the C++ compiler translates C++ code (source code) into machine language code (object code) by a sequence of conversions from numeric values to binary formats. Numeric data types (int, float, double etc.) are converted into binary format and stored into the computer’s memory. The character data types are similarly stored as numbers in computer’s memory and hence are also called the integral data type.

Character encoding is the process by which data types like char and string are internally represented by the computer as numerical codes. Each character is represented by an integer value that’s defined by standard agencies like the ASCII or Unicode. For example, ASCII/Unicode value 65 is interpreted as the character ‘A’, 66 as ‘B’ … 97 as ‘a’, 98 as ‘b’ … and so on.

A character (char) occupies 1 Byte of memory space in ASCII format. The char can occupy more than 1 Byte of memory space in Unicode format. Unicode efficiently handles both the 'char' and 'string' data types.

ASCII

ASCII (American Standard Code for Information Interchange) is the earliest standard format for character encoding. It represents characters or text matter for electronic/digital communication. Since ASCII works with 8 bits (1 Byte), it can process 8 bit (28 or 256) values. Therefore ASCII defines total 256 character codes(Refer to ASCII Values and Characters)

ASCII character codes from 0 to 31 (total 32) are control codes (non-printable). E.g. “Cancel Key” has ASCII code 24, “Escape Key” has value 27 etc.

ASCII character codes from 32 to 127 (total 96) are representable characters. E.g. ‘$’ has ASCII code 36, ‘A’ has ASCII code 65, ‘a’ has ASCII code 97 etc. The ASCII code 32 represents Blank Space, 127 represents DEL (delete) control key.

ASCII character codes from 128 to 255 (total 128) are extended ASCII values for complex characters. E.g ‘€’ has ASCII code 128, ‘TM’ has ASCII code 153 etc.

UNICODE

Unicode is the new standard format for character encoding. It represents characters or text matter for electronic/digital communication. Unicode works with more than 1 Byte of memory space and hence can usually process 8 bits, 16 bits or 32 bits of values with 28, 216 or 232 character codes respectively. A 16 bit Unicode uses 2 Bytes for encoding each character and a 32 bit Unicode uses 4 Bytes for encoding each character. (Refer to Unicode Chart)

Unicode has currently defined 143,924 character codes (143,696 graphic characters including emoji, 163 format characters and 65 control characters). 

It is a superset of ASCII and so, the first 256 character codes of Unicode are same as that of ASCII.

Unicode contains character codes for most written languages including left-to-right scripts like English, right-to-left scripts like Arabic, Chinese, Japanese etc.

BACKSLASH CHARACTERS

Backslash characters are character-constants used with the backslash to output certain special characters. The combination of a backslash with certain character constant is termed escape sequence. For example, \n is an escape sequence to print a new line.

Common Escape Sequences (other than \n) are listed below:

Escape
Sequence
\'

\"

\\

\a

\b

\t

\v
Description

single quote

double quote

backslash

audible bell

backspace

horizontal tab

vertical tab


PROGRAM 17: Write a program to accept a character from keyboard and print its corresponding ASCII/UNICODE value.


#include<iostream>
using namespace std;

main ()
{

  char ch;
  cout << "Enter a valid keyboard character: ";
  cin >> ch;
  cout << "\"ASCII\\UNICODE\" value of " << ch <<" is:  " << (int)ch;
   // Here, \" is escape sequence to print double quote…see output
   // Also, \\ is escape sequence to print backslash…see output

    }


Output 

           

    Enter a valid keyboard character:  

 

"ASCII\UNICODE" value of A is:  65 


CHAPTER EVALUATION EXERCISE


A) Choose the most appropriate answer (1 mark)

1. Data flow of extraction operator is from _____________

(a) LHS to RHS         (b) input device to storage          (c) a & b        (d) none

2. Output of sizeof('\n') and sizeof("\n") would be _____________ respectively.

(a) 1,2                      (b) 2,1              (c) 1,1                          (d) 2,2

3. The setfill() requires _____________ header file

(a) iostream             (b) iomanip        (c) string                   (d) conio

4. If p=5850, what would be the output of: setfill (‘-’)<<setw(7)<<p;

(a) ---5850               (b) 5850---        (c) --5850                 (d) ***5850

5. What are the outputs of:
  
   (i)  cout<<setprecision(2)<<1.278
   (ii) cout<<fixed<<setprecision(2)<<1.278;

(a) 1.3, 1.28             (b) 1.2, 1.27       (c) 1.2, 1.28             (d) 1.28, 1.27

6. What is output of following code:
  
   string str = " Test";
   cout << setfill('*') << setw(7) << str;

(a) ***Test               (b) ** Test            (c) Test***               (d) Test **

7. Manipulators are special stream functions that change _____________ format.

(a) only input           (b) only output       (c) input, output       (d) none of these

8. oct/hex/dec are related to setting the _____________

(a) width                   (b) fill character    (c) precision             (d) base value

9. ____________ is the default standard output device in C++

(a) Monitor             (b) Keyboard            (c) Mouse                 (d) Printer

10. The datatype "char" is ____________ and "String" is ____________

(a) primitive, builtin   (b) builtin, derived   (c) derived, userdefined    (d) primitive, userdefined

ANSWERS

1) c     2) a     3) b     4) a     5) a     6) b     7) c     8) d     9) a     10) d


B) State whether True or False (1 mark)

1. C++ stream used for data flow is an object.
2. New line manipulator "endl" occupies no memory space.
3. setbase(2) returns binary format of a number.
4. ASCII stores more character codes than UNICODE.
5. Escape sequence is used with output stream.

ANSWERS

1) True          2) True          3) False          4) False          5) True


C) Short answer questions (5 marks)

1. What are insertion and extraction operators.
2. What are backslash characters? List any 5 of them.

D) Subjective questions (10 marks)

1. Brief on five output manipulators.
2. What is character encoding? Describe ASCII and UNICODE formats.

No comments:

Post a Comment