0% found this document useful (0 votes)
27 views37 pages

Streams

The document provides an overview of streams in C++, detailing the flow of data, types of I/O operations (low level and high level), and the hierarchy of stream classes such as istream and ostream. It explains formatting flags, manipulators, and functions associated with the ios class for input and output operations. Additionally, it covers predefined stream objects, error handling, and examples of file handling using streams.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views37 pages

Streams

The document provides an overview of streams in C++, detailing the flow of data, types of I/O operations (low level and high level), and the hierarchy of stream classes such as istream and ostream. It explains formatting flags, manipulators, and functions associated with the ios class for input and output operations. Additionally, it covers predefined stream objects, error handling, and examples of file handling using streams.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Streams

1
Streams

Streams
Flow of data in the form of a sequence of bits
The main class for I/O operations is ios
istream and ostream are inherited from ios
iostream is inherited from istream and ostream
There are two types of I/O operations
a) Low level I/O
b) High level I/O

2
Streams

Low level I/O

 Unformatted data, series of bytes.

 byte wise transfer

 High speed, high volume, but inconvenient for people

3
Streams

High level I/O

- Formatted in terms of basic data types.

- bytes are grouped according to the data types for


transferring.

- Good for almost all I/O

4
Streams

Stream classes

istream: built-in input stream variable; by default connected to keyboard, cin

ostream: built-in output stream variable; by default connected to console, cout

5
iostream
hierarchy

6
Streams
Streams

iostream library

<iostream.h>: Contains cin, cout, cerr, and clog


objects.
<iomanip.h>: Contains parameterized stream manipulators.

<fstream.h>: Contains information important to user-


controlled file processing operations

7
Streams

Formatting Flags
• Formatting flags act as on/off switches that specify choices
for various aspects of input and output format and
operation.

8
Streams

Flags and their meaning

• skipws: Skip (ignore) whitespace on input


• left: Left-adjust output
• right: Right-adjust output
• dec: Convert to decimal
• oct: Convert to octal
• hex: Convert to hexadecimal
• boolalpha: Convert bool to “true” or “false” strings

9
Streams

• showbase: Use base indicator on output (0 for octal, 0x for hex)


• showpoint: Show decimal point on output
• uppercase: Use uppercase X, E, and hex output letters (ABCDEF)—
the default is lowercase
• showpos: Display + before positive integers
• scientific: Use exponential format on floating-point output
[9.1234E2]
• fixed: Use fixed format on floating-point output [912.34]

10
Streams

flags
• they are members of the ios class, you must usually precede them
with the name
• ios and the scope-resolution operator
• All the flags can be set
• using the setf() and unsetf() ios member functions

11
Streams

Manipulators

Manipulators are formatting instructions inserted directly into a stream.


For example endl

12
Streams

• ws Turn on whitespace skipping on input


• dec Convert to decimal
• oct Convert to octal
• hex Convert to hexadecimal
• endl Insert newline and flush the output stream
• ends Insert null character to terminate an output string
• flush Flush the output stream
• lock Lock file handle
• unlock Unlock file handle

13
Streams

Manipulators Argument Function


• setw() field width (int) Set field width for output
• setfill() fill character (int) Set fill character for
output
(default is a space)
• setprecision() precision (int) Set precision (number of
digits displayed)
• setiosflags() formatting flags (long) Set specified flags
• resetiosflags() formatting flags (long) Clear specified flags

14
Streams

Functions

• The ios class contains a number of functions that you can use to set
the formatting flags and perform other tasks.

15
Streams

• ch = fill(); Return the fill character (fills unused part of field;


default is space)
• fill(ch); Set the fill character
• p = precision(); Get the precision (number of digits displayed for
floating-point)
• precision(p); Set the precision
• w = width(); Get the current field width (in characters)
• width(w); Set the current field width
• setf(flags); Set specified formatting flags (for example, ios::left)
• unsetf(flags); Unset specified formatting flags
• setf(flags, field); First clear field, then set flags
16
Streams

main()
{ Output
int a = 589, b = 12345;
float e = 12345.1234; Hex 24d
char f = 'T';
Dec 589
cout << "\nHex " <<hex<<a ;
cout << "\nDec " <<dec<<a ; Oct 1115
cout << "\nOct " <<oct<<a ;

17
Streams

main()
{
int a = 589, b = 12345; Output
float e = 12345.1234; This is e 12345.1
char f = 'T'; 12345.123

cout << "\nThis is e "<<e <<endl ;


cout <<setprecision(9) << e<<endl;

18
Streams

main()
{
Output
int a = 589, b = 12345;
float e = 12345.1234;
char f = 'T'; 589
0000000589
cout << setw(10) << a <<endl;
cout << setfill('0');
cout << setw(10) << a << endl;

19
Streams

The istream Class


• The istream class, which is derived from ios, performs
input-specific activities, or extraction.

20
Streams

• >> Formatted extraction for all basic (and overloaded) types.


• get(ch); Extract one character into ch.
• get(str) Extract characters into array str, until ‘\n’.
• get(str, MAX) Extract up to MAX characters into array.

• get(str, DELIM) Extract characters into array str until specified


delimiter (typically ‘\n’). Leave delimiting char in stream.

• get(str, MAX, DELIM) Extract characters into array str until MAX
characters or the DELIM character. Leave delimiting char in stream.

21
Streams

• getline(str, MAX, DELIM) Extract characters into array str, until MAX
characters or the
• DELIM character. Extract delimiting character.
• putback(ch) Insert last character read back into input stream.
• ignore(MAX, DELIM) Extract and discard up to MAX characters until
(and including) the specified delimiter (typically ‘\n’).
• peek(ch) Read one character, leave it in stream.

22
Streams

• count = gcount() Return number of characters read by a (immediately


preceding) call to get(), getline(), or read().
• read(str, MAX) For files—extract up to MAX characters into str, until
EOF.
• seekg() Set distance (in bytes) of file pointer from start of file.
• seekg(pos, seek_dir) Set distance (in bytes) of file pointer from
specified place in file. seek_dir can be ios::beg, ios::cur, ios::end.
• pos = tellg(pos) Return position (in bytes) of file pointer from start of
file.

23
Streams

The ostream Class

• The ostream class handles output or insertion


activities.

24
Streams

• << Formatted insertion for all basic (and overloaded)


types.
• put(ch) Insert character ch into stream.
• flush() Flush buffer contents and insert newline.
• write(str, SIZE) Insert SIZE characters from array str into
file.
• seekp(position) Set distance in bytes of file pointer from
start of file.
• seekp(position, seek_dir) Set distance in bytes of file
pointer, from specified place in file. seek_dir can be
ios::beg, ios::cur, or ios::end.
• pos = tellp() Return position of file pointer, in bytes. 25
Files: Binary files, Text Files

• Hello Ali

• 21300 + 400+ 55.444 * 7

• ðÿ•œ±¾¤...݉JfIF

•.

26
Streams

using namespace std;

main()
{
int a = 589, b = 12345;
float e = 12345.1234;
char f = 'T';

ofstream csefile;
[Link] ("E:\\[Link]");
csefile<< " File Handling \n" ;
csefile<<a<<endl<<b<<endl<<e<<endl<<f;

}
27
Streams

using namespace std;

main()
{
int a = 589, b = 12345;
float e = 12345.1234;
char f = 'T';

ifstream csefile;
[Link] ("E:\\[Link]");
csefile>>a>>b>>e>>f;
cout<<" a =" << a <<endl;
cout<<" b =" << b <<endl; a =444
cout<<" e =" << e <<endl; b =789
cout<<" f =" << f <<endl; e =987.9
f =S

28
Streams

int main () {
ofstream csefile;
[Link] ("E:\\[Link]");
csefile << "This text directly goes to a file\n";
[Link]();
return 0;
}

29
Streams

using namespace std;

int main () {
int x=100, y = 300;
ofstream csefile;
[Link] ("E:\\[Link]"); The sum of x and y = 400

csefile << "The sum of x and y = " <<x+y;


[Link]();
return 0;
}
30
Streams

using namespace std;


int main () {
string ss;
ifstream fo ("E:\\[Link]");
if (fo.is_open())
{
getline (fo,ss);
cout << ss << '\n';
Output
[Link]();
This is our first text file.
}
else cout << "cannot open [Link]";
return 0;
}
31
Streams

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string ss;
ifstream fo ("E:\\[Link]");
if (fo.is_open())
{
while ( getline (fo,ss) )
{
cout << ss << '\n'; Output
} This is our first text file.
[Link](); This file contains the grades of two students.
} Fahad 3.3
else cout << "Unable to open file"; Sara 2.8
return 0;
}
32
Streams

Predefined Stream Objects

• These are automatically available when you include <iostream>.


• You don't need to create them — they are predefined globally.
• Based on classes like istream, ostream, and iostream.

33
Streams

• cin, an object of istream_withassign, normally used for keyboard


input
• cout, an object of ostream_withassign, normally used for screen
display
• cerr, an object of ostream_withassign, for error messages
• clog, an object of ostream_withassign, for log messages

34
Streams

Stream Errors

To deals with errors during stream operations

Error-Status Bits

• The stream error-status flags constitute an ios enum member that


reports errors that occurred in an input or output operation.

35
Streams

• goodbit: No errors (no flags set, value = 0)

• eofbit: Reached end of file

• failbit: Operation failed (user error, premature EOF)

• badbit: Invalid operation (no associated streambuf)

• hardfail: Unrecoverable error


36
Streams
Functions for Error Flags
• int = eof(); Returns true if EOF flag set

• int = fail(); Returns true if failbit or badbit or hardfail flag set

• int = bad(); Returns true if badbit or hardfail flag set

• int = good(); Returns true if everything OK; no flags set

• clear(int=0); With no argument, clears all error bits; otherwise sets


specified flags, as in

• clear(ios::failbit)
37

You might also like