0% found this document useful (0 votes)
34 views9 pages

C++ Unit 3 CHap 2

The document provides an overview of I/O streams in C++, explaining the stream concept, output and input operations, and the use of header files like `<iostream>`. It details both unformatted and formatted I/O operations, including examples of functions such as `getline()`, `get()`, `put()`, and formatting functions like `setprecision()` and `setw()`. Additionally, it discusses built-in classes for I/O, the `ios` class functions and flags, and demonstrates their usage through example programs.

Uploaded by

SushmaRaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views9 pages

C++ Unit 3 CHap 2

The document provides an overview of I/O streams in C++, explaining the stream concept, output and input operations, and the use of header files like `<iostream>`. It details both unformatted and formatted I/O operations, including examples of functions such as `getline()`, `get()`, `put()`, and formatting functions like `setprecision()` and `setw()`. Additionally, it discusses built-in classes for I/O, the `ios` class functions and flags, and demonstrates their usage through example programs.

Uploaded by

SushmaRaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

I/O STREAMS

INTRODUCTION TO I/O STREAMS

Stream Concept
• C++ I/O operations use the stream concept.
• The stream refers to a series of bytes or data flow.
• Streams improve performance by managing the flow of data between the main memory
 and devices like printers, screens, and network connections.
Output Operation
• Bytes are transferred from the main-memory to an output device (e.g., printer, screen)
during an output operation.
Input Operation
• Bytes flow from an input device (e.g., keyboard) to the main-memory during an
input operation.
Header Files for I/O
• C++ provides predefined functions and declarations through header files to handle
I/O tasks efficiently.
`<iostream>` Header File
• Essential for input/output operations in C++.
• Includes classes like `istream` (input stream) and `ostream` (output stream).
• Commonly used classes:
`cin`: Standard input stream.
`cout`: Standard output stream
Standard Output Stream (`cout`)
• An object of the `ostream` class, connected to the standard output device (typically
a display screen).
• Used with the insertion operator (`<<`), to display output on the console.
Standard Input Stream (`cin`)
• An object of the `istream` class, connected to the standard input device (typically a
keyboard).
• Used with the extraction operator (`>>`), to read input from the console.
Example
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
return 0;
}
Output:
Enter your age: 22
Your age is: 22
UNFORMATTED-I/O
Definition: Input- and output-operations where data is read or written without
applying any specific formatting-rules.
The data is transferred in its raw, unmodified form.
Purpose
• To perform simple, direct input- and output-operations without any concern for how
the data is presented or formatted.
• Useful for efficient, low-level data handling where formatting is not necessary.
Usage
• Often used when handling binary-data or performing low-level file operations.
• Provides more control over how data is managed and transferred, without altering its
format.
• Common unformatted-I/O functions are listed in below table:

getline(istream &input, string &str, char delim = '\n');


Description: This function reads a line-of-text from the input-stream and stores it
in a string.
It reads until it encounters a newline-character (`'\n'`) or the end of the file,
and then discards the newline-character.
Parameters:
`istream &input`: The input-stream from which the line is read (e.g., `cin`).
`string &str`: A reference to a `string` variable where the line-of-text will be
stored.
`char delim` (optional): A delimiter-character that specifies where the input
should stop. By default, it is `'\n'`.
• Example Usage: Demonstrating getline()
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
cout << "Enter a line-of-text: ";
getline(cin, line); // Reads a line-of-text from the user
cout << "You entered: " << line << endl; // Outputs the entered line
return 0;
}
Output:
Enter a line-of-text: Hello World
You entered: Hello World
get(char &ch)
• Description: This function reads a single character from the input-stream and
stores it in the variable `ch`.
• Parameters:
`char &ch`: A reference to a `char` variable where read character will be stored
put(char ch)
• Description: This function writes a single character to the output stream.
• Parameters:
`char ch`: The character to be written to the output stream.
• Example Usage: Demonstrating get() and put()
#include <iostream>
using namespace std;
int main() {
char c;
cout << "Enter a single character: ";
cin.get(c); // Reads a single character from the input
cout << "You entered: ";
cout.put(c); // Writes the character to the output
cout << endl;
return 0;
}
Output:
Enter a single character: A
You entered: A
read(char *buffer, streamsize count);`
• Description: This function reads a block of characters from the input-stream and
stores them in the array pointed to by `buffer`.
• Parameters:
`char *buffer`: A pointer to a character-array where the read characters will
be stored.
`streamsize count`: The maximum number of characters to read.
write(const char *buffer, streamsize count)
• Description: This function writes a block of characters from the array pointed to by
`buffer` to the output stream.
• Parameters:
`const char *buffer`: A pointer to a character-array containing the data to be
written.
`streamsize count`: The number of characters to write.
• Example Usage: Demonstrating read() and write()
#include <iostream>
using namespace std;
int main() {
char data[20];
cout << "Enter up to 20 characters: ";
cin.read(data, 20); // Reads up to 20 characters into the 'data' array
cout << "The data you entered: ";
cout.write(data, 20); // Writes 20 characters from 'data' to the output
cout << endl;
return 0;
}
Output:
Enter up to 20 characters: gcwmaddur
The data you entered: gcwmaddur

FORMATTED-I/O
• Definition: Input- and output-operations where data is formatted according to
specific rules or styles before being written to or read from a stream.
Purpose
• To present data in a readable and structured format.
• To ensure data is aligned, padded, or displayed in a particular way according to user
requirements.
Usage
• Formatted-I/O functions are used with output streams (cout) to control how data is
formatted when displayed.
• They can be applied to both numbers and text to ensure consistent and readable
output.
• Common formatted-I/O functions are listed in below table:

• Description: This function sets the number of digits to display after the decimal
point for floating-point numbers in the output stream.
• Parameters:
`int n`: The number of digits to display
• Example Usage:
cout << setprecision(3) << 3.14159; // Outputs: 3.14
setw(int width)
• Description: This function sets the width of the next input/output field. If the data
is shorter than the specified width, it will be padded with spaces or another character
(set by `setfill()`).
• Parameters:
- `int width`: The width of the field for the next input/output operation.
• Example Usage:
cout << setw(10) << 123; // Outputs: " 123" (7 spaces before 123)
setfill(char c)
• Description: This function sets the fill character used to pad fields in the output
stream. It is used in conjunction with `setw()` to pad the output with a specific
character instead of spaces.
• Parameters:
`char c`: The character used to pad the output field.
• Example Usage:
cout << setfill('*') << setw(10) << 1234; // Outputs:"1234" (padded with *)
Example Program: Demonstrating Formatted-I/O
#include <iostream>
#include <iomanip> // For setprecision, setw, and setfill
using namespace std;
int main() {
// Setting precision to 3 digits after the decimal point
cout << setprecision(3) << 3.14159 << endl; // Outputs: 3.14
// Setting width to 10 and displaying the number 123
cout << setw(10) << 123 << endl; // O/Ps: " 123" (7 spaces before 123)
// Setting fill character to '*' and width to 10, then displaying the number 1234
cout << setfill('*') << setw(10) << 1234 << endl; // Outputs: "******1234"
return 0;
}
Output:
3.14
123
******1234
Explanation:
- Precision Example: `setprecision(3)` formats the floating-point number
`3.14159` to show only 3 digits after the decimal point, resulting in `3.14`.
- Width Example: `setw(10)` sets the width of the field to 10 characters. Since the
integer `123` only takes up 3 characters, 7 spaces are added before it.
- Padding with Fill Character Example: setfill('*') << setw(10) << 1234 sets the
width of the output field to 10 characters and uses the asterisk (*) as the padding
character.
BUILT-IN CLASSES FOR I/O
Definition
• Built-in Classes for I/O handle input and output-operations.
• These classes simplify file and console I/O.
Features
• Stream-Based I/O: I/O-classes use streams to manage data flow.
This provides a consistent way to handle data from different sources like the
console or files.
• Overloaded Operators: I/O-classes support overloaded operators.
The `<<` operator is used for output, and the `>>` operator is used for input.
This makes it easy to format and handle data.
• Common built-in classes are listed in below table:
1) `iostream`
2) `istream`
3) `ostream`
1) `iostream`
• Description: The Base-class for input and output-stream classes.
• It provides functionalities for both input and output-operations.
• Derived-classes:
`istream`: For input-operations.
`ostream`: For output-operations.
2) `istream`
• Description: A class for input-stream operations.
• It is used for reading data from input-sources like the keyboard or files.
• Common Functions:
`>>` (extraction-operator) for reading formatted data.
`getline()` for reading lines of text.
`eof()` to check if the end of the input-stream is reached.
3) `ostream`
• Description: A class for output-stream operations.
• It is used for writing data to output-destinations like the console or files.
• Common Functions:
`<<` (insertion-operator) for writing formatted data.
`flush()` to flush the output buffer.
`endl` for inserting a newline and flushing the stream.
Example Program: Demonstrating istream and ostream
#include <iostream>
int main() {
int number;
cout << "Enter an integer: "; // Using ostream to print to console
cin >> number; // Using istream to read from keyboard
cout << "You entered: " << number << endl;
return 0;
}
Output:
Enter an integer: 42
You entered: 42

`ios` CLASS FUNCTIONS AND FLAGS


• Definition: The `ios` class is a Base-class for streams like `istream`, `ostream`,
and `fstream`.
• It provides functions and flags to manage stream operations.
Table: ios Class Functions

Table: ios Class Flags


Example Program: Demonstrating ios` Class Functions and Flags
#include <iostream>
#include <iomanip> // For formatting functions like setw, setprecision, etc.
int main() {
// Example of ios class functions and flags
// Stream state checking
cout << "Stream state checks:" << endl;
if (cout.good()) {
cout << "Stream is good." << endl;
}
if (cout.fail()) {
cout << "Stream has failed." << endl;
}
if (cout.eof()) {
cout << "End of file has been reached." << endl;
}
// Using flags
cout << "Hexadecimal and octal outputs:" << endl;
// Use hexadecimal formatting
cout << hex << "Hex: " << 255 << endl;
// Use additional flags
cout << "Additional flags:" << endl;
// Show base prefix
cout << showbase;
cout << "Hex with base: " << hex << 255 << endl;
// Show positive sign
cout << showpos;
cout << "Positive sign: " << 123 << endl;
return 0;
}
Output:
Stream state checks:
Stream is good.
Hexadecimal and octal outputs:
Hex: ff
Additional flags:
Hex with base: 0xff
Positive sign: +123
Explanation:
1) Stream State Checking:
• Checks the state of the stream with `good()`, `fail()`, and `eof()` methods.
2) Using Flags:
• `hex` formats numbers in hexadecimal.
• `oct` formats numbers in octal.
• `dec` resets the formatting to decimal.
• `showbase` displays the base prefix for hexadecimal (0x) and octal (0).
• `showpos` displays the positive sign for numbers.
3) Skipping Whitespace:
• Demonstrates `skipws`, though it's more relevant for input-streams. In the given
output, it shows how spaces are managed (not impactful in this specific context).

UNFORMATTED-I/O VS. FORMATTED-I/O

You might also like