26 Input-Output streams in C++
Jyotika Doshi
Introduction
This module introduces the ways to take input from standard input device (keyboard) and to write output on standard output device (screen). The module covers simple input/output operations using default formatting and unformatted binary input/output operations.
Main objective of this module is to develop basic skills of C++ input/output operations using input-output streams.
- Communication between Input-Output Devices and Program
Input-Output (I/O) operations are the basic need of any programming language. High-level programming languages provide device-independent I/O operations. They do not interact directly with I/O devices. Operating System (OS) interacts with device drivers of different I/O devices, receives input or sends output using I/O buffers to be used by program
1.1. C++ streams
In C++, I/O occurs in streams. Stream can be considered as an I/O buffer that can hold a series of bytes. A stream provides a serial interface to storage hiding the actual storage media device from high-level language (HLL) program. Stream structure is like a pipe. At the time of input, produced data is inserted in pipe at one end. At the time of output, data is extracted or consumed from other end of the pipe.
C++ provides input/output operations through a stream-based I/O library and the standard set of C-style I/O functions. Programmers may feel more comfortable to perform formatted I/O using scanf() and printf() functions of C language. C++ provides richer set of object-oriented I/O operations that are type-safe, easy to use and extendable.
The C++ IOStreams library is a part of the C++ standard library. It provides a uniform way of handling input from (and output to) any of the sources like keyboard, monitor, file, network etc. The stream-based I/O library can be availed using <iostream> file. Input/Output operations using stream structure is shown in the following figure.
1.2. Hierarchy of the I/O stream classes
Including <iostream> enables access to a whole hierarchy of classes responsible for providing I/O functionality. The class hierarchy of the I/O stream classes looks like this:
C++ streams: Class Hierarchy – Inheritance Diagram
Class ios_base is not based on a template and thus it is type-dependent. All other classes having name starting with word “basic” are template based classes providing type-independent I/O. Class ios_base describes the storage and member functions common to both input and output streams that do not depend on the template parameters. It manages formatting flags, state of the stream, and input/output exceptions.The template class basic_ios describes what is common and is dependent on template parameters. Each of the basic_xxxx classes is a class template. Thus class basic_ios and all its descendent are template based classes providing type-independent I/O. These classes can be instantiated with char or wchar_t character type. Thus C++ supports Unicode wide characters also. Class basic_ios contains a pointer to object of an arbitrary stream buffer. In C++, the stream buffer is technically accomplished by the class streambuf. Classes like ios, istream and ofstream are instantiated with char data type. Ex. class istream is defined as basic_istream <char> istream. Classes like wios, wistream and wofstream are instantiated with wide-character (wchar_t) type. Ex.class wofstream is defined as basic_ofstream <wchar_t> wofstream. Class ios_base and basic_ios provide low-level interface. Class basic_istream and basic_ostream provides formatting and other facilities. 1.3. Pre-defined streams
C++ supports normal ANSI narrow characters as well as Unicode wide characters. Thus, characters stored in the stream may be either one-byte narrow characters (char) or wide characters (wchar_t).
Objects used to communicate through the standard input and output devices are declared in <iostream> file and are available in to std namespace. Objects cin, cout, cerr and clog are declared for narrow character streams; whereas objects wcin, wcout, wcerr and wclog for wide-character streams.
Stream | Description | Device |
cin, wcin | standard input stream, provides buffered input, cin and wcin are the objects | Keyboard |
of class istream and wistream respectively | ||
cout, wcout | standard output stream, provides buffered output, cout and wcout are the | Screen |
objects of class ostream and wostream respectively | ||
cerr, wcerr | standard error stream, provides unbuffered output, cerr and wcerr are the | Screen |
objects of class ostream and wostream respectively | ||
clog, wclog | standard logging stream, provides buffered output, clog and wclog are the | Screen |
objects of class ostream and wostream respectively |
Buffered output is stored in a buffer and written out as a block, usually when full or flushed; whereas unbuffered output is handled immediately. Streams cerr and wcerr provides unbuffered output. So error messages are output immediately without getting buffered.
- Input/Output operations in C++
C++ supports formatted as well as unformatted input/output. Formatting features include specifying width, precision, alignment etc. I/O also requires conversion from binary to character and vice versa. In this section, we will learn I/O using default format. Default width=0 means that width is decided as per the content of the item. Default alignment is on left. User can explicitly specify formatting features; but that will be explained in later modules.
Input/Output operations in C++ can be performed using
- Overloaded shift operator: insertion (<< for output) and extraction (>> for input)
- Member functions: put(), get(), getline()
Unformatted I/O operations in C++ can be performed using read() and write() member functions.
- Input/Output operations using overloaded shift operators
Input operation reads data from input streams into variables in memory. Output operation moves data from memory variables to output stream (ostream). The direction of arrow in shift operator is from source to destination.
3.1. Output using Insertion operator (<<)
In output operation, data from main memory flows to an output device like screen, printer, disk drive, network connection through a stream. The insertion operator (<<) is used to put values from memory to output stream. For output on standard device, left shift (<<) operator is used with cout object. The predefined object cout is an instance of ostream class. Operator << is overloaded in ostream class. The stream associated with cout object is connected to the standard output device, usually a screen. In output operation, data is moved to output stream associated with object, say cout. So the direction of arrow is towards the destination cout. Ex. cout << data;
With output operation, first data is converted to a stream of character bytes. For example, consider number 65 stored in a variable of type short int. Number 65 is stored in memory as binary number 00000000 01000001. Before inserting data in the output stream, data is converted to characters ‘6’ (binary 00110110) and ‘5’ (binary 00110101).
Example:
cout << “ I like C++”; Notice the direction of shift operator. Direction shows flow of data from source to destination. Here source data “I like C++” is to be moved into the stream of cout object. As the data is inserted in the stream, << operator is called stream insertion operator. As cout object is in std namespace, it requires to include statement: using namespace std. As an alternative, it can be used with fully qualified name as std::cout. Insertion operator << associates from left to right. It returns a reference to its left-operand object (i.e. cout). Therefore, multiple insertion (<<) operations can be chained in a single statement.For example, cout << “ 5 x 6 = ” ; cout << 5*6; can be written as cout << “ 5 x 6 = ” << 5*6;
C++ provides type-safe I/O. In C, programmer needs to specify format code according to the data-type of the item to output. In C++, it is not so. This is possible because the << operator is overloaded in ostream class to output data items of built-in types integer, float, double, strings and pointer values.For user-defined objects to be used as items in the output using insertion operator, it requires overloading << operator in the corresponding class. For example, to output object time1 of myTime class using statement cout << time1; it requires to overload << in myTime class. This way, it makes it easy to use << operator to output user-defined objects.
Note that << operator does not add line breaks at the end of execution. To insert line break, output newline character ‘\n’ or use endl manipulator.
Example:
short x=10, y=20;
cout << x;
cout << y;
The output will be: 1020
To have line break, use
cout << x << endl;
cout << y;
The output will be:
10
20
In all above examples, numeric values are transformed to string of characters to be stored in stream using default format. See one more example given below. Default precision is 6 for real numbers. When it need more width, it converts it into scientific format with E notation.
cout << 123.45678 << endl << 1234.5678 << endl << 1234567.789 << endl;
Output:
123.457
1234.57
1.23457e+006
3.2. Input using Extraction operator (>>)
In input operation, data flows from input devices like keyboard, disk drive, network connection to main memory through a stream. Data entered from keyboard goes into a stream as characters. The extraction operator (>>) is used to read and remove values from the stream.
Here, first data is converted from a stream of character bytes to data type as to be stored in memory. For example, consider number 65 entered through keyboard. Entered characters ‘6’ and ‘5’ go in an input stream. If it is to be stored in a variable of type short int, it is to be converted to binary number 00000000 01000001 before storing it in memory. Thus, characters are extracted from an input stream attached to an input device, converted to a number and then stored in memory
For input from standard device, right shift (>>) operator is used with cin object. The predefined object cin is an instance of istream class. The stream associated with cin object is connected to the standard input device, usually a keyboard. Extraction operator is overloaded in istream class.
Like cout, cin object is also defined in std namespace. So, either include statement: using namespace std or use fully qualified name as std::cin.
Example:
short x;
cin >> x; // std::cin >> x;
Note the direction of extraction operator. The data is flowing from stream cin to variable in memory. Arrow is from source (cin) to destination (memory variable), so cin >> variable. It is called extraction operator, as data is extracted from a stream and stored in a variable.Here, the characters introduced using the keyboard are transmitted in the stream till ENTER (or RETURN) key is pressed.The type of the variable written after >> operator determines how to interpret the characters read from the input stream and convert it. This type-safe operation is possible due to >> overloaded in istream class for various built-in data types like integer, float, double, strings and pointer values. For use of
- >> operator to input objects of user-defined class, user needs to overload operator >> in the corresponding class.
The extraction operator in C++ ignores leading whitespace characters. The most common whitespace characters are: newline (‘\n’), tab (‘\t’), blank or space, carriage return (‘\r’), vertical tab (‘\v’). The extraction operator will scan leading whitespace characters from the input stream and discard them.
Extraction stops when any invalid character is encountered in case of numeric values or white-space character in case of strings.
Consider following code. Assume the input from keyboard as 12 17.3 19 <Enter>.
int A, B;
double X;
cin >> A; // A <— 12
cin >> X; // X <— 17.3
cin >> B; // B <— 19
The entered characters: 12 17.3 19 <enter> will be stored in stream cin.
When cin >> A is executed, it starts extracting characters from cin. As A is of type int, it will extract digit characters 12 and terminates due to occurrence of space character. String of characters ‘1’ and ‘2’ is converted to binary and stored in int variable A.
Note that the input stream is not flushed after a read operation. So, executing next statement cin >> X will start extracting from current position in cin stream. As X is of type double, extraction will terminate after reading characters 17.3. These characters are converted to double and stored in X. Similarly characters 19 are extracted as a result of cin >> B and stored in B after converting to int. Thus, as a result of executing above code, contents of A, X and B will be 12, 17.3 and 19 respectively.
Now, look at the following code. Considering the input 12 1.3 19 <Enter>, content of A, B and C will be 12, ‘1’, and ‘.’ respectively. As explained above, leading spaces before first 1 are ignored, scanning stops at space after 2 and extracted characters 12 are stored in A after converting them to binary; B and C being of character data type, 1 is extracted and stored in B; next character . is extracted and stored in C.
int A;
char B, C;
cin >> A; // A <— 12
cin >> B; // B <— ‘1’
cin >> C; // C <— ‘.’
Remember that leading spaces are ignored and the input stream is not flushed after a read operation.
Note that these operators do not do validation. So, if the user enters something unexpected, it may result in garbage values for the variable. For example, the type of variable is int and entered characters are X12. Here, input character X in non-numeric and cannot be interpreted as an integer, so the extraction operation fails. It lets the program continue without setting a value for variable. Thus, it is programmer’s responsibility to test whether an operation has succeeded or not. One way to perform this test is using member function fail() of stream class. It returns true if an error has occurred. But, this is an overhead in program execution.
Try following code with invalid input, say jk and see the result.
int x=10;
cout << “Enter number:”;
cin >> x;
if (cin.fail())
cout << “Input failed, x is ” << x;
else
cout << “Input succeeded, x is ” << x;
Extraction operator >> associates from left to right. It returns zero (false) when EOF (End-Of-File) is encountered, otherwise returns reference to the object from which it was invoked (i.e. cin). Thus, it can be cascaded to have multiple items to input using single statement.
Refer following code with cascaded extraction in single statement: cin >> name >> marks; is
equivalent to two statements: cin >> name; cin >> marks; char name[30];
cout << “\nEnter name and marks:”;
cin >> name >> x ;
cout << “name ” << name << “, marks: ” << x;
Note that EOF can be entered from keyboard as CTRL+Z or CTRL+z for DOS/Windows/Mac OS and CTRL+d for Unix/linux based OS. See the example of using EOF to terminate the loop.
#include <iostream>
using namespace std;
int main()
{
int x, sum=0;
cout << “Enter number \n”;
cout << “End with CTRL+Z\n”;
while (cin >> x) sum = sum + x;
cout << “Sum of numbers is ” << sum;
}
Output:
Enter number
End with CTRL+Z
7
5
3
1
4
^Z
Sum of numbers is 20
- Input/output (with default format) using member functions of I/O streams
Here, some member functions of istream and ostream class are explained. Functions put() enables output operations; whereas functions get() and getline() used for input operations. In the following examples, the output of the C++ code is as a result of execution on Visual C++.
4.1. Output using member functions put()of ostream class Function put() of ostream class writes single character ch to the output stream. Syntax: ostream& ostream::put (char ch) This function returns a reference to ostream. So put() can be chained to output more than one characters in a single statement.
Ex. cout.put(‘A’);
cout.put(‘A’).put(‘B’).put(‘C’);
In C/C++, character is treated as an integer. So function put() may be called with an ASCII-valued expression also. Ex. cout.put(65);
4.2. Input using member functions get(), getline() of istream class We will see two forms of overloaded function get() to read single character and one more version of get() to read an array of characters. Function getline() can also be used to read an array of characters.
4.2.1. Read single character from input stream using get() with no argumentsSyntax: int istream::get ()
Ex. int ch = cin.get(); When get() is used without argument, it scans the input stream for a single character and returns the scanned character as unsigned char in int. It reads whitespace also. Remember that extraction operator
- >> considers whitespace as terminating character and so cannot read it. Returning int type enables characters like EOF also to be returned.
Consider the following code using extraction operator. If input is 9<Enter>, it assigns extracted 9 to x and then wait for non-whitespace input character for ch. But, if input is 9p, it assigns 9 to x and p to ch without waiting for another input.
int x;
cin >> x;
char ch;
cin >> ch;
In above code, change last line to ch=cin.get(); Here, get() function can extract whitespace also. Thus, if input is 9<Enter>, it assigns extracted 9 to x and then assigns whitespace character to ch.
4.2.2. Read single character from input stream using get() with single argument
Syntax: istream& istream::get (char& c)
Ex. char ch; cin.get(ch);
The parameter in this form of get() is a reference variable of character data type. The extracted character is assigned to the character variable in the argument. This version of get() reads whitespace character also just like get() without argument.
The function returns a reference to istream and so it can be cascaded to read more characters in a single statement.
Ex. char ch1, ch2, ch3; cin.get(ch1).get(ch2).get(ch3);
4.2.3. Read array of character from input stream using get() with three parameters
The extraction operator with cin terminates scanning as soon as whitespace occurs. Thus, it can read words but not lines or paragraphs. This problem can be solved using another form of get() with at three parameters as well as using getline() and read() functions.
Syntax: istream& istream::get (char* str, int count, char delim=’\n’)
This form of get() function requires at least first two arguments. Third argument is optional. It specifies a delimiter and the default value is newline character. The first parameter is a C-type string where extracted characters are stored. It may be a pointer of type char, unsigned char or signed char. Note that it is not an object of C++ string class.
The second argument specifies how many characters to read.
Function get() reads up to (count -1) characters from the input stream and stores into the array pointed by str. Reading is terminated either by reaching the limit of (count-1) or delimiter or EOF.
Note that the delimiter is not extracted and it remains available in the stream for next extraction.Regardless of which condition terminates the read, string str gets termination character `\0′ at the end of the string.As get() returns a reference to istream class, multiple get() can be chained in single statement. Array str should be large enough to store read characters. If not, it may corrupt next memory locations by overwriting. Try following code with str1[2] and see the effect.Refer following code and its output when entered string is “Mera Bharat Mahan Hai”.
char str1[10], str2[30];
cout << “\nTesting get, enter string:”;
cin.get(str1,4).get(str2,8);
cout << “str1:” << str1 << “\nstr2:” << str2 << endl; cout << “\nTesting get with delimiter, enter string:”; cin.get(str1,8,’h’).get(str2,10);
cout << “str1:” << str1 << “\nstr2:” << str2 << endl;
Output:
Testing get, enter string:Mera Bharat Mahan Hai
str1:Mer
str2:a Bhara
Testing get with delimiter, enter string:str1:t Ma
str2:han Hai
In the above code,
Executing statement cin.get(str1,4).get(str2,8);
- Delimiter is not used, so default is ‘\n’ which appears after last character ‘i’
- Call get(str1,4) extracts 3 characters from stream and assigns to str1 appending string terminator character null, thus str1 is “Mer”
- Call get(str2,8) extracts next 7 characters from stream starting from ‘a’ and assigns to str2 appending terminator character ‘\0’, thus str2 is “a Bhara”Executing statement cin.get(str1,8,’h‘).get(str2,10);
- It starts scanning from character ‘t’ available in the stream. Due to delimiter ‘h’ occurring before 7 characters; scanning stops at ‘h’ assigning “t Ma” to str1 after appending string terminator
- Default delimiter ‘\n’ occurs before next 9 characters, scanning stops at newline character assigning “han Hai” to str2 after appending string terminator Note that reading with get() do not extract delimiter from the stream. Next extraction starts from the position of delimiter onwards.
4.2.4. Read array of character from input stream using getline()member function
Syntax: istream& istream::getline (char * str, int count, char delim=’\n’).
All parameters are same as those used with form of get() with three parameters. Even though it seems like get() function to read a string, it differs as follows:
- In getline(), the delimiter is extracted from the stream if it is encountered before (count-1) characters. An extracted delimiter is discarded, i.e. delimiter is extracted but not stored in str.
- If delimiter is not found before specified number of characters or end of file, getline() sets the ios::fail flag as well as the ios::eof flag if appropriate. Refer following C++ code and its output on various runs when executed on Visual C++:
char str1[10], str2[30];
cout << “Testing getline, enter string in two lines:”; cin.getline (str1,6);
if (cin.fail()) cout << “\ncin.getline (str1,6) failed”;
else cout << “str1:” << str1 << endl;
cin.getline(str2,15);
if (cin.fail()) cout << “\ncin.getline (str2,15) failed”;
else cout << “str2:” << str2 << endl;
Output of run1:
Testing getline, enter string in two lines:ThankGod
cin.getline (str1,6) failed
cin.getline (str2,15) failed
Explanation: while executing cin.getline(str1,6), delimiter (default ‘\n’) is not found before 6 characters, so failed. Once fail bit is set, it remains in effect in next getline() also. To clear the fail bit, one may use clear() function. Function clear() can be used to reset the status flag associated with the stream.
Insert statement cin.clear() before second getline() call and see the change in the output.
Output of run 2:
Testing getline, enter string in two lines:Thank You
cin.getline (str1,6) failed
cin.getline (str2,15) failed
Explanation: Here, white space occurs after 5th character; but specified delimiter (default ‘\n’) is not found before 6 characters, so getline(str1,6) failed.
Output of run 3:
Testing getline, enter string in two lines:Thank
str1:Thank GOD
str2:GOD
Explanation: While executing cin.getline(str1,6), delimiter (default ‘\n’) is found before 6 characters, so succeeded. Similarly, second getline() succeeded as istream ends.Now, change the statement cin.getline (str1,6); to cin.getline (str1,10); and execute the code. See the effect of count 10 in the result as follows:Testing getline, enter string in two lines:ThankGOD
str1:ThankGOD
Bless me
str2:Bless me
What happens when reading number and then a string? Execute following code snippet with input 1234<enter>.
int dummyInt;
string dummyString;
cin >> dummyInt;
getline(cin, dummyString);
See that dummyString is empty. Why?
Explanation: When executing cin >> dummyInt; extraction operator stops at whitespace and 1234 is assigned to dummyInt. Now, when getline() is executed, it starts scanning from whitespace (<Enter> is ‘\n’ and CR) from istream and finds ‘\n’ as delimiter. Delimiter is extracted from stream but not stored in dummyString.
- Unformatted Input/output operations using member functions of I/O streams
Unformatted I/O reads or writes raw bytes without performing any conversion or formatting. Functions read() and write() provides unformatted input and output respectively. Function read() is a member of istream class; whereas function write() is a member of ostream class. In the following examples, the output of the C++ code is as a result of execution on Visual C++.
5.1. Input using member functions read()
Function read() is used to perform binary read operations. It reads a string of raw bytes from input stream.
Syntax: istream& istream::read (char * str, int count)
First parameter is a C-type string. It may be pointer to char, unsigned char or signed char.
The read function is useful for binary stream input. It reads bytes from input stream until count limit is reached or EOF is reached.
Reading is not affected by newline or any other delimiter as in case of get() or getline().
Unlike get() or getline(), string terminating character ‘\0’ is not appended in str.
If the istream ends before reading count bytes, read() sets the ios::fail flag. Thus, encountering end-of-file during the read is considered as an error.
char str1[10], str2[30];
cout << “Testing read(), enter string:”;
cin.read(str1,6);
if (cin.fail())
cout << “\ncin.read (str1,6) failed”;
else
cout << “str1:” << str1 << endl;
cin.read(str2,15);
if (cin.fail())
cout << “\ncin.read (str2,15) failed”;
else
cout << “str2:” << str2 << endl;
Output of run1:
Testing read(), enter string:Thank GOD
str1:Thank ╠╠╠╠╠╠╠╠╠╠q☺▒`↑°8
Bless Me
str2:GOD
Bless Me
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Thank ╠╠╠╠╠╠╠╠╠╠q☺▒`↑°8
Explanation: Here input is “Thank GOD” and then “Bless Me”. An execution of cin.read(str1,6) extracts 6 bytes from stream and does not insert terminating character. So, output of str1 continues till it finds end of str1, i.e. till it finds ‘\0’ character. Thereafter, execution of cin.read(str2,15) starts scanning from current position in stream at ‘G’ and reads characters GOD\nBless Me in str2. Again, string terminating character is not inserted in str2, so outputs till it finds null character.
Remember: If string terminating is necessary, it is programmer’s responsibility to add.
Function gcount() can be used to know the number of characters read in last read() operation. It will help the programmer to determine the position to place string terminating character ‘\0’.
Syntax: int istream::gcount ()
It returns number of characters read from istream in the last unformatted input operation.
Modify above code as follows and see the output:
char str1[10], str2[30];
cout << “Testing read(), enter string:”;
cin.read(str1,4);
cout << “Number of characters read is ” << cin.gcount() << endl;
if (cin.fail())
cout << “\ncin.read (str1,4) failed”;
else
{
str1[cin.gcount()]=’\0′;
cout << “str1:” << str1 << endl;
}
cin.read(str2,15);
if (cin.fail())
cout << “\ncin.read (str2,15) failed”;
else
{
str2[cin.gcount()]=’\0′;
cout << “str2:” << str2 << endl;
}
Output:
Testing read(), enter string:Thank God, Bless Me
Number of characters read is 4
str1:Than
str2:k God, Bless Me
Explanation: Function gcount() is used to know the number of characers read. It is used to know the position where to insert string terminating character ‘\0’. Function read() do not add string terminating character; so ‘\0’ character is inserted in the array strings str1 and str2 explicitly at proper position.
5.2. Output using member functions write()
Function write() of ostream class is used to write an array of characters to output stream. Syntax: ostream& ostream::write (const char* str, int count)
This function writes count number of characters from the C-type string str to output stream. Note that the string to output should be C-type string (char *). First argument may be a pointer to char or unsigned char or signed char. The write() function performs unformatted binary output. It inserts raw bytes from C-type string to output stream. Since the data is unformatted, if string termination character appears before count number of characters, it is also written to the stream as raw byte. Refer the following code and its output. First write() call writes 20 bytes from str1 to output stream as raw bytes. With second write() call, array contains 5 characters which is less than specified count 7 to output. Here, it writes 7 bytes with two blanks after Hello.
char str1[30]=”Trying: \n Write function\n”;
cout.write(str1, 20);
cout.write(“Hello”, 7).write (“How \n are you?”, 20).cout.write (“I am Fine”, 10);
Output of the above code is as follows:
Trying:
Write funcHello How
are you? I am Fine
Behaviour of write() is undefined if the size of the first argument (array str) is less than count characters (including any terminator). In the above code, modify the statement cout.write(str1, 20); to cout.write(str1, 35); Observe the following output as a result of an attempt to write 35 bytes from an array of 30 bytes.
Trying:
Write function
╠╠╠╠╠Hello How
are you? I am Fine
As write() functions returns a reference to ostream, it can be cascaded for multiple output in a single statement as used in above code.Example: cout.write(“Hello”, 7).write (“How \n are you?”, 20).cout.write (“I am Fine”, 10); 5.3. Advantages of using Binary I/O In binary I/O, an int is stored in 4 bytes, whereas its text version might be “98712345”, requiring 8 bytes. Similarly, a float is stored in 4 bytes, while its formatted version might be “6.702314e17”. Binary I/O is more efficient as it does not require conversions between binary and text. Numbers are stored as they are in the memory, rather than as strings of characters.
Note:
In this module, the most frequently used functions are explained with examples. There are many other functions available with istream and ostream. Reader may refer the manual or other literature. Learning this module will make it easy for reader to learn more functions.
Summary
- Input/output operations using default format can be performed using overloaded shift operator and member functions of istream and ostream class.
- Extraction operator terminates extraction at white-space character.
- Insertion operator do not insert blank line at the end.
- Function put() is a member of ostream class and is used to write a single character
- Functions get() with no parameter and get() with single parameter can be used to read a single character. These functions can read white-space also. Using get() with single parameter returns a reference to its calling object, here istream, so it can be cascadded.
- Functions get() with three parameters and getline() can be used to read array of chacaters into a C-type string. They terminate string by appending null character ‘\0’.
- Function get() with three parameters do not extract the delimiter from the stream. Delimiter remains available in the stream for next extraction.
- Function getline() extract the delimiter from the stream but do not store it in the string. Delimiter is not available in the stream for next extraction.
- Function read() and write() performs unformatted I/O by reading or writing raw bytes respectively. Function read() do not append null character in the string.
References
1) Stanley Lippmann, “C++ Primer”, Pearson Education.
2) Bjarne Stroustrup, “The C++ Programming Language”, Pearson Education.
3) Scott Mayer, “Effective C++”, Addison Wesley.
4) Bhushan Trivedi , Programming with ANSI C++, 2/e , Oxford University Press.
5) Yashavant P. Kanetkar “Let Us C++” , Bpb Publications.
6) Abhiram G. Ranade, “An Introduction to Programming through C++” , McGraw Hill
7) Ellis and B. Stroustrup “Annotated C++ Reference Manual”, http://www.stroustrup.com/arm.html
8) Herbert Schildt, “Complete Reference C++”, McGraw Hill Publications.
9) Ashok Kamthane, “Object Oriented Programming with ANSI and Turbo C++”, Pearson Education
10) E Balaguruswami, “Object Oriented Programming With C++”, Tata McGraw Hill
“C++ FAQs”, Pearson Education