×

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples.

C++ Standard Input/Output:

User-program communication is made possible by C++’s usage of input and output (I/O) operations. During these processes, information is transferred between input devices (such as keyboards) and output devices (such as display screens). The C++ Standard Library includes functions to perform these operations using stream-based input and output techniques.

C++ standard input/output operations are performed to flow bytes stream from the keyboard (input device) to the main memory and from the main memory to the display screen (output device), respectively. The input/output is done using standard libraries provided by C++.

Standard Input (cin):

The command that manages the C++ standard input is called “Console input”, or cin. The iostream library includes the cin object, which is used to read data from the keyboard. The retrieved data is then saved in a variable for subsequent use. Cin is used to accept input via the >> operator (extraction operator).

Example syntactical code:

Let us take an example to illustrate the Cin Object in C++.

#include <iostream>

using namespace std;

int main() {

    int number;

    cout << "Enter a number: ";

    cin >> number;  // Taking input from the user

    cout << "You entered: " << number << endl;

    return 0;

}

Output:

Enter a number: 5

You entered: 5

Standard Output (Cout):

The C++ standard output is controlled by the cout object, which stands for “console output”. It is also a part of the iostream library and is used to display results on the screen. Cout employs the << operator (insertion operator) to send data to the output stream.

Syntax:

It has the following syntax:

cout << "Hello, World!";

This command prints "Hello, World!" into the screen. You can use cout to display several values by linkage << operators.

C++ I/O Library Header Files:

LibraryDescription
<iostream>This library defines cin, cout, cerr,and clog objects for input stream, output stream, un-buffered error stream, buffered error stream respectively.
<fstream>This library defines file declares services for user-controlled file processing.
<iomapin>This library declares services useful for performing formatted I/O such as setw and setprecision.

1. <iostream> library:

The library, which provides functionality for handling common input and output operations, is part of the C++ Standard Library. It includes predefined items such as:

  1. Cin: It is used for standard input (keyboards) operations.
  2. Cout: It is used for standard output (keyboards) operations.
  3. Cerr: It is used for error output that is unbuffered, meaning that errors are seen right away.
  4. Clog: It is used for buffered error output, which logs and displays errors as they occur.

Console-based applications use this library to enable seamless data transfer between the user and the system. In its stream-based communication architecture, data flows from sources like the keyboard (cin) to memory and from memory to the display (cout). Because it enables structured input/output, the iostream library is crucial for any C++ program that requires user interaction.

Example:

Let us take an example to illustrate the Cin and Cout Object in C++.

#include <iostream>

using namespace std;

int main() {

    cout << "Enter a number: ";

    int num;

    cin >> num;

    cout << "You entered: " << num << endl;

    return 0;

}

2. <fstream> Library:

In C++, the library offers features for managing file input and output operations. Programs may read from and write to files due to it, which enables long-term data storage. There are three main classes defined by the library:

  1. ifstream: It is used for reading data from files.
  2. ofstream: It is used for writing data to files.
  3. fstream: A combination of both, allowing reading and writing.

In C++, file handling consists of opening a file, reading and writing data, and then closing the file. Data integrity and memory leak prevention are ensured by proper file handling.

Example code:

Let us take an example to illustrate the Cin and Cout Object in C++ using <fstream> library.

#include <fstream>

#include <iostream>

using namespace std;

int main() {

    ofstream file("example.txt"); 

    file << "Hello, File I/O!"; 

    file.close(); 

    return 0;

}

This program creates and adds data to a file named example.txt. The library is crucial for applications that require data persistence outside of program execution.

3. <iomanip> Library:

The functions in the library allow us to change the format of input and output operations. It is frequently used to improve readability by formatting textual and numerical output. Important functions consist of:

  1. setw(n): It sets the width of the output field.
  2. setprecision(n): It defines the number of decimal places for floating-point numbers.
  3. fixed: It ensures floating-point numbers use fixed-point notation.
  4. showpoint: It forces the display of decimal points.

Example Code:

Let us take an example to illustrate the Cin and Cout Object in C++ using <iomanip> library.

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

    double num = 3.14159;

    cout << "Without setprecision: " << num << endl;

    cout << "With setprecision(2): " << fixed << setprecision(2) << num << endl;

    return 0;

}

Output:

Without setprecision: 3.14159

With setprecision(2): 3.14

The application in question formats the floating-point value to two decimal places. Applications written in C++ require the library in order to provide output that is precise and organized.

Conclusion:

In conclusion, C++ input and output operations must be understood to develop interactive and efficient programs. With support for standard input (cin), output (cout), and error management (cerr, clog), the library facilitates seamless user-application connection. A crucial part of persistent data management and the package extends these capabilities to file handling by enabling the saving and retrieval of data from external files via ofstream, ifstream, and fstream. Setw(), setprecision(), and fixed are some of the advanced formatting methods available in the <iomanip> library that provide precise and organized output, which is very useful in scientific and financial applications. These libraries assist programmers in writing more trustworthy, approachable, and well-organized programs by providing the foundation for C++ I/O operations. Programmers must comprehend these ideas to create effective C++ programs with effective data input, storage, and presentation.


Related Topics

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

3 minutes read.

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

Structure of C++ Program

Many people believe that C++, an object-oriented programming (OOP) language, is the finest language for developing demanding applications. A superset of the C language is C++. Java, a closely comparable...

4 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

Program that produces different results in C and C++

Introduction: There are many such programs that compile run both in C and C++ but give different outcomes when compiled by the C and C++ compilers. There are a variety of such...

6 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

C++ If

C++ Control Statement C++ control statement or decision-making statement is used to control the flow of program statement according to condition applied. C++ if Control Statement An if control statement in C++ is used to...

2 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.