Advanced
Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Top tech companies experts provide live online training

Learn Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Back to home
Logicmojo - Updated Jan 12, 2024



Introduction

Standard input-output stream is referred to as iostream. The declaration of objects by #include iostream governs reading from and writing to the standard streams. The iostream library, then, is an object-oriented library that uses streams to offer input and output functions.
Streams are collections of bytes. You can consider it to be an abstraction of a gadget. Through this abstraction, I/O operations can be carried out on the device. In order to perform input and output from a C++ programme, you must include the iostream header file.


#include The most popular standard input and output streams, cin and cout, are provided by iostream. The following is the syntax for using them: Syntax


1. cout-- Standard Output Stream

It belongs to the ostream class. It outputs to the display screen, which is the default output device. To add data to the standard output stream cout, which has to be displayed on the screen, we must use the stream insertion operator <<
Syntax :

cout << variable_name;

OR:

cout << variable1 << variable2 << ... ;

Cascading is the process of employing numerous stream insertion operators with a single cout. It makes it easier to print several variables next to one another on the same line.

What if you wish to simultaneously cascade and print on different lines? There are two ways to accomplish this, both of which work with string literals as well:

1. Using \n, the new line character


Syntax :

cout << variable1 << '\n' << variable2

It will print Variable 1 value and print new line and then Variable 2 value on next line.

2. Using endl, the manipulator


Syntax :

cout << variable1 << endl << variable2;

In C++, a manipulator modifies an input or output stream's behaviour. The std namespace's endl manipulator has a new line insertion function.

2. cin-- Standard input Stream

It belongs to the istream class. It reads input from the keyboard, which is the common input method. For the purpose of extracting keyboard-entered data, we must employ the stream extraction operator >>.
Syntax :

cout << variable_name;

OR:

cin >> variable1 >> variable2 >> ... ;

Cascading can also be done with Cin to extract numerous variables.

Examples

1. C++ Program using cout


#include <iostream>
using namespace std;

int main() {
    string name = "Sam Piter";

    // you can use cout with a variable and also insert a line character
    cout << name << '\n';

    // or you can also insert the output direcly to the screen
    cout << "This is a sample text inserted into the output screen...";

    return 0;
}

Output :

Sam Piter
This is a sample text inserted into the output screen...

The ostream object cout, which is connected to the display screen, is used in the code cout. Before the variable name, the stream insertion operator "" writes its value onto the screen. Another follows it, printing an escape sequence to move the pointer to a new line. Moreover, you can use cout to output to write several items on a single line. The value from the new line is first inserted in the final cout statement, which makes use of a string literal.


2. C++ Program using cin


#include <iostream>
using namespace std;

int main() {
    int a, b, sum;

    cout << "Enter first number: ";
    // read input from standard input device, usually, the keyboard
    cin >> a;

    cout << "Enter second number: ";
    // read another input from the keyboard
    cin >> b;

    sum = a + b;

    cout << "The sum of the two numbers is " << sum;

    return 0;
}

Output :

Enter first number: 25
Enter second number: 35
The sum of the two numbers is 60

The software mentioned above performs I/O operations using cin and cout. Yet, understanding cin, the istream object associated to an input device, is the major goal here (usually, the keyboard). The user-inputted number is extracted from cin after being asked to submit the first number. This extraction is carried out by the stream extraction operator ">>". The value is saved in the variable after the operator, i.e., a, following a successful data extraction. For extracting the second integer variable b, the process is similar. The total of the numbers is then printed.

How iostream Works in C++?

Any C++ program's potential to accept keyboard input from the user and display output on the screen is its primary fundamental feature. To comprehend how this data flow works through the objects defined in #include iostream, you must be familiar with input and output streams.

1.Input Stream

Bytes must move from the device to the main memory in order for it to happen, We call this process input. A source of bytes is an input stream object, such as cin. Istream, Ifstream, and Istringstream are the three most significant input stream classes.

2.Output Stream

It involves the transfer of bytes from the device's main memory. This process can be called as output . It operates in opposition towards how input stream functions.Bytes can go to an output stream object (like cout).The classes ostream, ofstream, and ostringstream are the most crucial output stream types.

Global Stream Objects of C++ iostream

There are various pre-defined stream classes in C++ that deal with handling files and I/O. Stream objects are the products of stream classes. A programme can access a variety of these items worldwide thanks to the iostream library. Global stream objects are those available on a worldwide scale.

#include Iostream declares the following two sets of eight global stream objects:

1. Narrow Characters

They focus on bytes. Internally, the objects uses the char type, which may hold 256 values and is mapped to a specific entry in ASCII table. They occupy less memory ( 8-bits ). This group's members are the objects cin, cout, cerr, and clog.


a. Cin

It is an istream class object. It regulates data extraction from the user's input, or standard input stream, as a stream of bytes. Istream object as the return value.
Syntax :

// var can be a variable of type narrow string
cin >> var;

b. Cout

It is an ostream class object. It manages printing output, or inserting data into the standard output stream as a stream of bytes. Ostream object as the return value.
Syntax :

cout << var;

c. cerr

It is an ostream class object. To show or publish the error messages, a standard error output stream that is not buffered is utilized. Ostream object as the return value.
Syntax :

cerr << "An error occured!";

d. clog

It is an ostream class object. It is a standard error output stream that has been buffered and is mostly used for logging. Ostream object as the return value.

2. Wide Characters

They have a wide focus. Internally, the objects employ the wchar t type, which is equivalent to UNICODE values and has a far greater value range than the char type. International language symbols are supported. Compared to little characters, they take up more memory (depending on the compiler used they may take 2 or 4 bytes ). This group includes the following items: wcin, wcout, wcerr, and wclog.


a. wcin

It is a wistream class object. It uses a wide stream but regulates input extraction similarly to cin. Wistream object as the response value.
Syntax :

// here, the var can be a type of wide string
wcin >> var;

b. wcout

It is a Wostream class object. It uses a wide stream but controls data insertion similarly to cout. Wostream object as the return value.
Syntax :

wcout << var;

c. wcerr

This item belongs to the wostream class. It uses a wide stream and is an unbuffered standard error output stream comparable to cerr. Object wostream as the return value.
Syntax :

wcerr << L"An error occurred";

d. wclog

It is a Wostream class object. It uses a broad stream but is still a buffered standard error output stream, like clog. Wostream object as the return value.
Syntax :

wclog << L"Logging a message...";

Why should We Use iostream Instead of the Traditional cstdio?

A wealth of features are unlocked by C++ I/O with and >>. It is more useful to #include iostream in a C++ programme for the reasons listed below:

1.Enhanced Type Safety

When using include iostream, the compiler being used to conduct I/O operations determines the object type statically. As opposed to utilizing% to identify this types dynamically.

2.Less Errors

You no longer require superfluous% tokens to be consistent with the object type being I/O'd thanks to C++ I/O capabilities. Errors are decreased when redundancy is removed.

3.Extensions

Now, without altering the existing code, you may easily input and output the user-defined kinds.

4. Inheritence

Real classes like std::ostream and std::istream are provided by the #include iostream. You can create user-defined types and related objects with the same properties as streams by inheriting from them. The programmer has the freedom to adjust the logic as necessary thanks to this flexibility. Using the FILE* function of cstdio is absolutely unrelated to this idea.

Conclusion

1. C++'s #include iostream function provides the fundamental I/O capability. Streams are utilised by all I/O operations.

2. The iostream classes' main idea is the stream. A stream object can be compared to a smart file that serves as both a source and a destination for bytes.

3. The most popular iostream class objects, which employ common input and output streams, are cin and cout.

4. Narrow and Broad character streams are the other global stream objects listed by include iostream.

5. The wide character utilises wchar t while the narrow character uses char as its data type.

6. Wide characters are made up of wcin, wcout, wcerr, and wclog while narrow characters are made up of cin, cout, cerr, and clog.

7. Examples of ostream and wostream are the cout, cerr, clog, and their wide counterparts.

8. The cin and wcin are examples of the respective streams, istream and wistream.

9. Clog is buffered and more effective than cerr, which is unbuffered. As a result, clog is mostly used for logging whereas cerr is utilised to write serious errors. This also applies to wcerr and wclog.

10. #include iostream should be chosen over cstdio because it is more extendable, type-safe, and reduces mistakes.








Frequently Asked Questions (FAQs)



A preprocessor directive in the C++ programming language is #include iostream. It contains the iostream library, which offers the fundamental input/output features in C++. This directive gives you access to other related features as well as the common input/output stream objects cin and cout.



Because it permits input and output operations in C++, the #include iostream directive is crucial. You won't be able to use the common input/output stream objects and associated iostream library features without inserting this directive.

1. You can communicate with the user by reading console input and showing output.

2. It offers a practical method for carrying out fundamental input and output operations in C++.

3. Since input and output operations are necessary for the majority of applications, it is a fundamental component of C++ programming.



Input and output operations in C++ are performed using the iostream library. It has features for reading input from the user or outside sources and for writing output to the console or other locations. Predefined stream objects like cin (for input) and cout (for output), available in the iostream library, let you interact with the user and show information on the screen.

The C++ input/output operations process is made simpler by the iostream library. It offers a simple, standardized method of communicating with users and displaying data. The iostream library is crucial for managing input and output in C++ programs, whether you need to read user input, show output, or format the data being processed.



In C++, the quantity of header files is not fixed nor predetermined. Numerous header files that offer different functionalities and features are available in the C++ standard library. Additionally, user-defined programs and third-party libraries may both include their own header files. The actual amount of C++ header files that are accessible depends on the individual libraries and code that are utilized in a given project or program.



YA header file in C++ is a file that includes declarations, definitions, and other details about variables, constants, classes, functions, and other things that can be used across different source code files. Between the source code file and the outside code or libraries, it serves as an interface. The header file's contents are copied into the source code file during the preprocessing stage when the header file is included using the #include directive. This enables the compiler to recognize and comprehend the declarations and definitions. For instance, the declarations and definitions for input/output stream objects like cin and cout, which can be used in numerous C++ source files, are found in the header file "iostream".



The C++ preprocessor substitutes that line with the contents of the iostream header file when you use the #include iostream directive to include the iostream library. The declarations and definitions required for input/output stream objects and associated functions are contained in this header file..

Important information:

• Prior to your C++ code being really compiled, the #include directive is processed by the preprocessor.

• It instructs the preprocessor to substitute the content of the designated header file in the #include line.

• #include iostream makes the declarations and definitions from the iostream header file available for use in your program including them.



No, the C++ programming language is the only one that supports the #include iostream directive. Other programming languages cannot understand it or process it. Typically, each programming language has a unique method for incorporating libraries or modules.



There are alternatives to using #include iostream, which is the most used directive for input/output operations in C++. Using the input/output procedures of the C library headers like "stdio.h" is one such method. However, these substitutes might differ from the iostream library in terms of syntax and functionality.



C++ offers a number of other standard libraries that you can use in your projects in addition to the iostream library. The libraries "cmath" for mathematical operations, "string" for string manipulation, "vector" for dynamic arrays, and "fstream" for file input/output operations are some of the more often used ones.



The #include iostream directive can be used in header files, yes. You can use input/output stream objects and associated functionality in functions or classes declared in header files by including iostream. However, since big header files like iostream might lengthen compilation times, it is generally thought to be a good practice to keep their inclusion to a minimum.



There is a difference between including user-defined or project-specific headers inside double quotes ('" "') and including system headers inside angle brackets (' >'). When you use "iostream>," the preprocessor looks in the system include directories for the header file. However, when you use "iostream," the preprocessor first looks in the current directory or any project-specific include directories before looking in the system include directories.



The #include iostream directive and the iostream library are only available in the C++ programming language, not in the C programming language itself. For input/output operations in C, you would normally utilize the'stdio.h>' header. Programming languages C and C++ are two separate dialects with differing syntax and resources.



The term "iostream" is an abbreviation for "input/output stream." The "io" stands for "input/output," and "stream" denotes a constant data stream between a program and an outside source, such as a user or file. The required functions and objects for carrying out input and output operations are provided by the C++ iostream library, making it simpler to manage data input and output in a program.



The C++ preprocessor instruction "include iostream>" includes the iostream header file. This directive enables you to access features like input and output stream objects (cin and cout) offered by the iostream library.

The phrase "using namespace std" instructs the compiler to utilize the std namespace in the code. The standard C++ library functions and objects are defined under the std namespace. You can utilize the names of objects and functions from the std namespace without having to explicitly indicate it each time by using this statement. When using the iostream library, for instance, you don't have to write "std::cout" and "std::cin," just "cout" and "cin."



The preprocessor directive "#include iostream>" in this code includes the iostream library. The main function, which acts as the starting point for a C++ program, has a function declaration of "int main()". The actual logic and instructions for your program would be written in the code included within the main function. The "return 0;" sentence is used to show that the program has run successfully.


Logicmojo Learning Library