C++ Stream Input/Output

Page Contents:

What Is C++ Stream Input/Output?
Advantages of I/O files
Streams
Classic Streams
Standard Streams
iostream library header files
The Output of char *Variable
The member function put
Stream Input
Stream Output
get and getline function in C++
Istream Member Functions Peek,Putback And Ignore
Type-Safe I/O
Stream Manipulators
Integral Stream Base: Dec,Oct,Hex And Setbase
Field Width(Width,Setw)
Stream Format States And Stream Manipulators
Justification (Left, Right And Internal)
Padding (Fill,Setfill)
Integral Stream Base(Dec,Oct,Hex,Showbase)
Floating-Point Numbers; Scientific And Fixed Notation(Scientific, Fixed)
Tying An Output Stream To An Input Stream

What is C++ Stream input/output?

The C++ standard libraries provide an extensive set of input/output capabilities.C++ uses type-safe I/O. Each I/O operation is executed in a manner sensitive to the data type. If an I/O member function has been defined to handle a particular data type, then that member function is called to handle that data type. If there is no match between the type of the actual data and a function for handling that data type, the compiler generates an error.

Users can specify how to perform I/O for objects of programmer-defined types. This extensibility is one of C++’s most valuable features.

Advantages of I/O files

  • Use the C++ style I/O exclusively in C++ programs, despite the fact that C-style I/O is available to C++ programmers
  • C++ I/O is type-safe
  • C++ enables a common treatment of I/O for predefined types and programmer-defined types. This commonality facilitates software development and reuse
  • Also unformatted I/O for the best performance in high-volume file processing

Streams

C++ I/O occurs in streams, which are sequences of bytes. In input operations, the bytes flow from a device(e.g. a keyboard, a disk drive, a network connection) to the main memory. In output operations, bytes flow from main memory to a device(e.g. a display screen, a printer, a disk drive, a network connection, etc).

An application associates meaning with bytes. The bytes could represent characters, raw data, graphic images, digital speech, digital video or any other information an application may require.

The system I/O mechanisms should transfer bytes from devices to memory(and vice versa) consistently and reliably. Such transfers often involve some mechanical motion, such as the rotation of a disk or tape, or the typing of keystrokes at a keyboard. The time these transfers take is typically much greater than the time the processor requires to manipulate data internally. Thus, I/O operations require careful planning and tuning to ensure maximum performance

C++ provides both “low-level” and “high-level” I/O capabilities.Low-level I/O capabilities(i.e. unformatted I/O) specify that some number of bytes should be transferred device-to-memory or memory-to-device.In such transfers, the individual byte is the item of interest. Such low-level capabilities provide high-speed, high-volume transfers, but are not particularly convenient for programmers.

Programmers generally prefer a higher-level view of I/O(i.e. formatted I/O), in which bytes are grouped into meaningful units, such as integers, floating-point numbers, characters, strings, and programmers-defined types. These type-oriented capabilities are satisfactory for most I/O other than high-volume file processing

Classic Streams

The C++ classic stream libraries enabled input and output of chars. Because of a char occupies one byte, it can represent only a limited set of characters. However, many languages use alphabets that contain more characters than a single-byte char can represent. The ASCII character set does not provide these characters; the Unicode character set does.

Standard Streams

C++ includes the standard stream libraries, which enable developers to build systems capable of performing I/O operations with Unicode characters. For this purpose, C++ includes an additional character type called wchar_t, which can store Unicode characters. The C++ standard also redesigned the classic C++ stream classes, which processed only chars, as a class template with separate specializations for processing characters of types char and wchar_t, respectively.

iostream library header files

The C++ iostream library provides hundreds of I/O capabilities. Several headers files contain portions of the library interface.

Most C++ programs include the <iostream> header files, which declares basic services required for all stream I/O operations. The <iostream> header file defines the cin,cout,cerr, and clog objects, which corresponds to the standards input stream, the standard output stream, the unbuffered standard error stream, and the buffered standard error stream, respectively. Both unformatted and formatted-I/O services are provided.

The <iomanip> header declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision.

The <fstream> header declares services for the user-controlled file processing.

The Output of char *Variable

C++ determines data types automatically, an improvement over C.Unfortunately, this feature sometimes “gets in the way.” For example, suppose we want to print the value of a char* to a character string (i.e. the memory address of the first character of that string). However, the << operator has been overloaded to print data of type char* as a null-terminated string. The solution is to cast the char* to a void*

Program for printing the address stored in a char* variable

#include<iostream>
using std::cout;
using std::endl;
int main()
{
char *word="test";
cout<<"Value of word is:"<<word<<endl;
    <<"Value of static_cast <void *>(word) is:"
    <<static_cast<void *>(word)<<endl;
return 0;
}

OUTPUT:

Value of word is:test
Value of static_cast<void *>(word) is:0046C070

The member function put

We can use the put member function to output characters. For example, the statement

cout.put('A');

displays a single character A.Calls to put may be cascaded, as in the statement

cout.put('A').put('\n');

which outputs the letter A followed by a newline character. As with <<, the preceding statement executes in this manner, because of the dot operator( . ) evaluates from left to right, and the put member function returns a reference to the ostream object that received the put call .The put function also may be called with a numeric expression that represents an ASCII value, as in the statement cout.put(65); which also output A.

Stream Input

Formatted and unformatted input capabilities are provided by istream.The stream-extraction operator(i.e. the overloaded>>operator) normally skips whitespace characters(such as blanks, tabs, and newlines) in the input stream; we will see how to change this behavior. The stream-extraction operator returns 0(false) when end-of-file is encountered on a stream; otherwise, the stream-extraction operator returns a reference to the object that received the extraction message(e.g. cin in the expression cin>>grade).Each stream contains a set of state bits used to control the state of the stream(i.e. formatting, setting error states, etc.).Stream extraction causes the stream’s failbit to be set if data of the wrong type is input and causes the stream’s badbit to be set if the operation fails.

Stream Output

Formatted and unformatted output capabilities are provided by ostream. Capabilities for output include the output of standard data types with the stream-insertion operator(<<); the output of characters by the put member function; unformatted output by the writing member function output of integers in decimal, octal and hexadecimal formats output of floating-point values with various precision with forced decimal points, in scientific notation and in fixed notation; output of data justified in fields of designated widths; output of data in fields padded with specified characters; and output of uppercase letters in scientific notation and hexadecimal notation.

get and getline function in C++

The get member function with no arguments inputs one character from the designated stream and returns this character as the value of the function call.
This version of get returns EOF when end-of-file on the stream is encountered.

Write a Program using member functions get,put and eof(end of file)

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int character;
cout<<"Before input, cin.eof() is"<<cin.eof()<<endl
    <<"Enter a sentence followed by end-of-file:"<<endl;
while((character=cin.get())!=EOF)
cout.put(character);
cout<<"\nEOF in this system is:"<<character<<endl;
cout<<"After input, cin.eof() is"<<cin.eof()<<endl;
return 0;
}

OUTPUT:

Before input, cin.eof() is 0
Enter a sentence followed by end-of-file:
Testing the get and put member functions
Testing the get and put member functions
^z
EOF in this system is:-1
After input cin.eof() is 1 

Write a Program contrasting input of a string by cin and cin.get

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
const int SIZE=80;
char buffer1[SIZE];
char buffer2[SIZE];
cout<<"Enter a sentence:"<<endl;
cin>>buffer1;
cout<<"\nThe string read with cin was"<<endl
    <<buffer1<<endl<<endl;
cin.get(buffer2,SIZE);
cout<<"The string read with cin.get was:"<<endl
    <<buffer2<<endl;
return 0;
}

OUTPUT:

Enter a sentence:
Contrasting string input with cin and cin.get
The string read with cin was:
Contrasting
The string read with cin.get was:
string input with cin and cin.get

Write a Program Inputting characters using cin member function getline

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
const int SIZE=80;
char buffer[SIZE];
cout<<"Enter a sentence:"<<endl;
cin.getline(buffer,SIZE);
cout<<"\nThe sentence entered is:"<<endl<<buffer<<endl;
return 0;
}

OUTPUT:

Enter a sentence:
The sentence is hello
The sentence entered is:
The sentence is hello 

istream Member Functions peek,putback and ignore

the ignore member function of istream either reads and discards a designated number of characters or terminates upon encountering a designated delimiter(the default delimiter is EOF, which cause ignore to skip to the end of the file when reading from a file).
The putback member function places the previous character obtained by a get from an input stream back into that stream.This function is useful for applications that scan an input stream looking for a field beginning with a specific character.When that character is input, the application returns the character to the stream, so the character can be included in the input data.
The peek member function returns the next character from an input stream, but does not remove the character from the stream.

Type-Safe I/O

C++ offers type-safe I/O. The << and >> operators are overloaded to accept data items of specific types. If unexpected data is processed, various error bits are set, which the user may test to determine whether an I/O operation succeeded or failed. This enables the program to stay in control

Stream manipulators

C++ provides various stream manipulators that perform formatting tasks. The stream manipulators provide capabilities such as setting field widths, setting precision, setting, and un-setting format state, setting the fill character in fields, flushing streams, inserting a newline into the output stream(and flushing the stream), inserting a null character into the output stream and skipping whitespace in the input stream.

Write a Program using unformatted I/O using read,gcount and write

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
const int SIZE=80;
char buffer[SIZE];
cout<<"Enter a sentence:"<<endl;
cin.read(buffer,20);
cout<<endl<<"The sentence entered was:"<<endl;
cout.write(buffer,cin.gcount());
cout<<endl;
return 0;
}

OUTPUT:

Enter a sentence:                                                                        The sentence is hello                                                                    The sentence entered was:
The sentence is hell  

Integral Stream Base: dec,oct,hex and setbase

Integers are interpreted normally as decimal(base-10) values.To change the base in which integers are interpreted on a stream, insert the hex manipulator to set the base to hexadecimal or insert the oct manipulator to set the base to local.Insert the dec manipulator to reset the stream base to decimal.
The base of a stream also may be changed by the setbase stream manipulator, which takes one integer argument of 10,8 or 16 to set the base to decimal,octal or hexadecimal, respectively.Because setbase takes an argument, it is called a parameterized stream manipulator.Using setbase takes an argument, it is called a parameterized stream manipulator.Using setbase requires the inclusion of the header file.The stream base value remains the same until changed explicity

Program using stream manipulators hex, Oct, Dec, and set base

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
using std::hex;
using std::dec;
using std::oct;
#include<iomanip>
using std::setbase;
int main()
{
int number;
cout<<"Enter a decimal number:";
cin>>number;
cout<<number<<"in hexadecimal is:"<<hex
    <<number<<endl;
cout<<dec<<number<<"in octal is:"
     <<oct<<number<<endl;
cout<<setbase(10)<<number<<"in decimal is:"
    <<number<<endl;
return 0;
}

OUTPUT:

Enter a decimal number:10                                                                10in hexadecimal is:a
10in octal is:12                                                                         10in decimal is:10 

Write a Program Floating-Point Precision(precision, set precision)

We can control the precision of floating-point numbers by using either the setprecision stream manipulator or the precision member function of ios_base. A call to either of these sets the precision for all subsequent output operations until the next precision-setting call. A call to a member function precision with no argument returns the current precision setting.

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
using std::fixed;
#include<iomanip>
using std::setprecision;
#include<cmath>
int main()
{
double root2=sqrt(2.0);
int places;
cout<<"Square root of 2 with precision 0-9"<<endl
    <<"precision set by ios_base member-function"
    <<"precision:"<<endl;
cout<<fixed;
for(places=0;places<=9;places++)
{
cout.precision(places);
cout<<root2<<endl;
}
cout<<"\nPrecision set by stream-manipulator"
    <<"setprecision:"<<endl;
for(places=0;places<=9;places++)
cout<<setprecision(places)<<root2<<endl;
return 0;
}

OUTPUT:

1.41421356
1.414213562 
Precision set by stream manipulatorsetprecision:                                                                 

1                                                                                        1.4                                                                                      1.41                                                                                     1.414                                                                                    1.4142
1.41421
1.414214                                                                                 1.4142136                                                                                1.41421356                                                                               1.414213562  

Field Width(width,setw)

The width member function (of base-class ios_base) sets the width of the field (i.e. the number of characters positions in which value should be output or the maximum number of characters that should be input) and returns the previous width. If values output is narrower than the field width, fill characters are inserted as padding. A value wider than the designated width will not be truncated the full number will be printed.

Write a program demonstrating member function width

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int widthValue=4;
char sentence[10];
cout<<"Enter a sentence:"<<endl;
cin.width(5);
while(cin>>sentence)
{
cout.width(widthValue++);
cout<<sentence<<endl;
cin.width(5);
}
return 0;
}

OUTPUT:

Enter a sentence:                                                                        This sentence is for demo                                                                This                                                                                       sent                                                                                      ence                                                                                        is                                                                                       for                                                                                      demo 

Programmer-Defined Manipulators

#include<iostream>
using std::ostream;
using std::cout;
using std::flush;
ostream& bell(ostream& output)
{
return output<<'\a';
}
ostream& carriageReturn(ostream& output)
{
return output<<'\r';
}
ostream& tab(ostream& output)
{
return output<<'\t';
}
ostream& endLine(ostream& output)
{
return output<<'\n'<<flush;
}
int main()
{
cout<<"Testing the tab manipulator"<<endLine
    <<'a'<<tab<<'b'<<tab<<'c'<<endLine;
cout<<"Testing the carriageReturn and bell manipulators:"
    <<endLine<<".........";
cout<<bell;
cout<<carriageReturn<<"......"<<endLine;
return 0;
}

OUTPUT:

Testing the tab manipulator:
a       b       c
Testing the carriageReturn and bell manipulators:
 .........

Stream Format States and Stream Manipulators

Various stream manipulators can be used to specify the kinds of formatting to be performed during stream-I/O operations. Stream manipulators control the output’s format settings.

The stream manipulators are:

Stream ManipulatorDescription
skipws Skip whitespace characters on an input stream
left Left justify output in a field.Padding characters appear to the right if necessary
right Right justify output in a field.Padding characters appear to the left if necessary
internal Indicate that a number’s sign should be left justified in a field and a number’s magnitude should be right justified in that same field
dec Specify that integers should be treated as decimal(base 10) values.
oct Specify that integers should be treated as octal(base 8) values.
hex Specify that integers should be treated as hexadecimal(base 16) values.
showbase Specify that the base of a number is to be output ahead of the number
showpoint Specify that floating-point numbers should be output with a decimal point.This is used normally with fixed to guarantee a certain number of digits to the right of the decimal point, even if they are zeros.
uppercase Specify that uppercase letters should be used in the hexadecimal integer and that uppercase E should be used when representing a floating-point value in scientific notation
showpos Specify that positive numbers should be preceded by a plus sign(+).
scientific Specify output of a floating-point value in scientific notation
fixed Specify output of a floating-point value in fixed-point notation with a specific number of digits to the right of the decimal point.

Write a Program showpoint to control the printing of trailing zeros and decimal points for doubles

#include<iostream>
using std::cout;
using std::endl;
using std::showpoint;
int main()
{
cout<<"Before using showpoint"<<endl
    <<"9.9900 prints as:"<<9.9900<<endl
    <<"9.9000 prints as:"<<9.9000<<endl
    <<"9.9000 prints as:"<<9.0000<<endl<<endl;
cout<<showpoint
   <<"After using showpoint"<<endl
   <<"9.9900 prints as:"<<9.9900<<endl
   <<"9.9000 prints as:"<<9.9000<<endl
   <<"9.0000 prints as:"<<9.0000<<endl;
return 0;
}

OUTPUT:

Before using showpoint
9.9900 prints as:9.99                                                                    9.9000 prints as:9.9
9.9000 prints as:9                                                                                                              
After using showpoint                                                                    9.9900 prints as:9.99000                                                                 9.9000 prints as:9.90000
9.0000 prints as:9.00000 

Justification (left, right and internal)

Stream manipulators left and right enable fields to be left-justified with padding characters to the right or right-justified with padding characters to the left, respectively. The padding characters are specified by the fill member function or the setfill parameterized stream manipulators

Write a Program demonstrating left justification and right justification

#include<iostream>
using std::cout;
using std::endl;
using std::left;
using std::right;
#include<iomanip>
using std::setw;
int main()
{
int x=12345;
cout<<"Default is right justified:"<<endl
    <<setw(10)<<x;
cout<<"\n\nUse std::left to left justify x:\n"
    <<left<<setw(10)<<x;
cout<<"\n\nUse std::right to right justify x:\n"
    <<right<<setw(10)<<x<<endl;
return 0;
}

OUTPUT:

 Default is right justified:                                       
     12345
Use std::left to left justify x:
12345                                                                                    Use std::right to right justify x:
        12345 

Write a Program to print an integer with internal spacing and plus sign

#include<iostream>
using std::cout;
using std::endl;
using std::internal;
using std::showpos;
#include<iomanip>
using std::setw;
int main()
{
cout<<internal<<showpos<<setew(10)<<123<<endl;
return 0;
}

OUTPUT:

+     123

Padding (fill,setfill)

The fill member function specifies the fill character to be used with justified fields; if no value is specified, spaces are used for padding. The fill function returns the prior padding character. The setfill manipulator also sets the padding character.

#include<iostream>
using std::cout;
using std::endl;
using std::showbase;
using std::left;
using std::right;
using std::internal;
using std::hex;
using std::dec;
#include<iomanip>
using std::setw;
using std::setfill;
int main()
{
int x=10000;
cout<<x<<"printed as int right and left justified\n"
    <<"and as hex with internal justification\n"
    <<"Using the default pad character (space):"<<endl;
cout<<showbase<<setw(10)<<x<<endl;
cout<<left<<setw(10)<<x<<endl;
cout<<internal<<setw(10)<<hex<<x<<endl<<endl;
cout<<"Using various padding characters:"<<endl;
cout<<right;
cout<<fill('+');
cout<<setw(10)<<dec<<x<<endl;
cout<<left<<setw(10)<<setfill('%')<<x<<endl;
cout<<internal<<setw(10)<<setfill('*')<<hex
    <<x<<endl;
return 0;
}

OUTPUT:

10000 printed as int right and left justified
and as hex with internal justification.
Using the default pad character(space):
    10000
10000
0x   2710
Using various padding characters:
*****10000
10000%%%%%
0x^^^^2710
 

Integral Stream Base(dec,oct,hex,showbase)

C++ provides stream manipulators dec, hex, and oct to specify that integers are to be displayed as a decimal, hexadecimal and octal values, respectively. Stream insertions default to decimal if none of these manipulators are used. Integers prefixed with 0 (zero) are treated as octal values, integers prefixed with 0x and 0X are treated as hexadecimal values and all other integers are treated as decimal values. Once a particular base is specified for a stream, all integers on that stream are processed using that base until a different base is specified or until the program terminates.

Stream manipulator showbase forces the base of integral value to be output. Decimal numbers are output by default, octal numbers are output with a leading 0 and Hexa-decimal numbers are output with either a leading 0x or a leading 0X

Floating-Point Numbers; Scientific and Fixed Notation(scientific, fixed)

Stream manipulators scientific and fixed control the output format of floating-point numbers.Stream manipulator scientific forces the output of a floating-point number in scientific format. Stream manipulator fixed forces a floating-point number to display a specific number of digits(as specified by the member function precision or stream-manipulator setprecision) to the right of the decimal point.Without using another manipulator, the floating-point-number value determines the output format.

Write a Program using stream-manipulator showbase

#include<iostream>
using std::cout;
using std::endl;
using std::showbase;
using std::oct;
using std::hex;
int main()
{
int x=100;
cout<<"Printing integers preceded by their base:"<<endl
    <<showbase;
cout<<x<<endl;
cout<<oct<<x<<endl;
cout<<hex<<x<<endl;
return 0;
}

OUTPUT:

Printing integers preceded by their base:
100
0144
0x64

Tying an Output stream to an Input Stream

Interactive applications generally involve an istream for input and an ostream for output. When a prompting message appears on the screen, the user responds by entering the appropriate data. Obviously, the prompt needs to appear before the input operation proceeds. With output buffering, outputs appear only when the buffer fills when outputs are flushed explicitly by the program or automatically at the end of the program.C++ provides a member function tie to synchronize the operation of an istream and an ostream to ensure that outputs appear before their subsequent inputs. The call

cin.tie(&cout);

ties cout(an ostream) to cin (an istream).Actually, this particular call is redundant, because C++ performs this operation automatically to create a user’s standard input/output environment. However, the user would tie other istream/ostream pairs explicitly.To untie an input stream, inputStream, from an output stream, use the call

inputStream.tie(0);

Translate »