The Wayback Machine - https://web.archive.org/web/20240907062959/https://www.geeksforgeeks.org/basic-input-output-c/
Open In App

Basic Input / Output in C++

Last Updated : 15 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

C++ comes with libraries that provide us with many ways for performing input and output. In C++ input and output are performed in the form of a sequence of bytes or more commonly known as streams.

  • Input Stream: If the direction of flow of bytes is from the device(for example, Keyboard) to the main memory then this process is called input.
  • Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device( display screen ) then this process is called output.

Basic Input / Output in C++


Header files available in C++ for Input/Output operations are: 

  1. iostream: iostream stands for standard input-output stream. This header file contains definitions of objects like cin, cout, cerr, etc.
  2. iomanip: iomanip stands for input-output manipulators. The methods declared in these files are used for manipulating streams. This file contains definitions of setw, setprecision, etc.
  3. fstream: This header file mainly describes the file stream. This header file is used to handle the data being read from a file as input or data being written into the file as output.
  4. bits/stdc++: This header file includes every standard library. In programming contests, using this file is a good idea, when you want to reduce the time wasted in doing chores; especially when your rank is time sensitive. To know more about this header file refer this article.

In C++ after the header files, we often use ‘using namespace std;‘. The reason behind it is that all of the standard library definitions are inside the namespace std. As the library functions are not defined at global scope, so in order to use them we use namespace std. So, that we don’t need to write STD:: at every line (eg. STD::cout etc.). To know more refer this article.

The two instances cout in C++ and cin in C++ of iostream class are used very often for printing outputs and taking inputs respectively. These two are the most basic methods of taking input and printing output in C++. To use cin and cout in C++ one must include the header file iostream in the program.

This article mainly discusses the objects defined in the header file iostream like the cin and cout.  

  • Standard output stream (cout): Usually the standard output device is the display screen. The C++ cout statement is the instance of the ostream class. It is used to produce output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<).
C++
#include <iostream>

using namespace std;

int main()
{
    char sample[] = "GeeksforGeeks";

    cout << sample << " - A computer science portal for geeks";

    return 0;
}

Output: 

GeeksforGeeks - A computer science portal for geeks

In the above program, the insertion operator(<<) inserts the value of the string variable sample followed by the string “A computer science portal for geeks” in the standard output stream cout which is then displayed on the screen.

  • standard input stream (cin): Usually the input device in a computer is the keyboard. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. 
    The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.
C++
#include <iostream>
using namespace std;

int main()
{
    int age;

    cout << "Enter your age:";
    cin >> age;
    cout << "\nYour age is: " << age;

    return 0;
}

Input : 

18

Output: 

Enter your age:
Your age is: 18

The above program asks the user to input the age. The object cin is connected to the input device. The age entered by the user is extracted from cin using the extraction operator(>>) and the extracted data is then stored in the variable age present on the right side of the extraction operator.

  • Un-buffered standard error stream (cerr): The C++ cerr is the standard error stream that is used to output the errors. This is also an instance of the iostream class. As cerr in C++ is un-buffered so it is used when one needs to display the error message immediately. It does not have any buffer to store the error message and display it later.
  • The main difference between cerr and cout comes when you would like to redirect output using “cout” that gets redirected to file if you use “cerr” the error doesn’t get stored in file.(This is what un-buffered means ..It cant store the message)
C++
#include <iostream>

using namespace std;

int main()
{
    cerr << "An error occurred";
    return 0;
}

Output: 

An error occurred


  • buffered standard error stream (clog): This is also an instance of ostream class and used to display errors but unlike cerr the error is first inserted into a buffer and is stored in the buffer until it is not fully filled. or the buffer is not explicitly flushed (using flush()). The error message will be displayed on the screen too.
C++
#include <iostream>

using namespace std;

int main()
{
    clog << "An error occurred";

    return 0;
}

Output: 

An error occurred


 Related Articles:  


 



Previous Article
Next Article

Similar Reads

Input/Output Operators Overloading in C++
Operator Overloading is a part of Polymorphism, which enables the feature because of which we can directly use operators with user-defined classes and objects. To read more about this, refer to the article operator overloading in C++. Input/Output Operators(&gt;&gt;/&lt;&lt;) Overloading in C++ We can't directly use the Input/Output Operators (&gt;
2 min read
Output of C++ Program | Set 10
Predict the output of following C++ programs.Question 1 C/C++ Code #include&lt;iostream&gt; #include&lt;string.h&gt; using namespace std; class String { char *p; int len; public: String(const char *a); }; String::String(const char *a) { int length = strlen(a); p = new char[length +1]; strcpy(p, a); cout &lt;&lt; &quot;Constructor Called &quot; &lt;
2 min read
Code valid in both C and C++ but produce different output
There are some syntactical structures that are valid for both C and C++ but different behavior when compiled and run in the both languages. Several differences can also be exploited to create code that compile in both languages but behave differently. For example, the following function will return different values in C and C++: Example Codes valid
2 min read
Printing Output in Multiple Lines in C++
This article focuses on discussing how to use cout for multi-line printing. This can be easily done using any of these two methods: Using endl.Using \n. Let's discuss each of these methods in detail. Using endl The endl statement can be used to print the multi-line string in a single cout statement. Below is the C++ program to show the same: C/C++
2 min read
Output of C++ Program | Set 14
Predict the output of following C++ program. Difficulty Level: Rookie Question 1 #include &lt;iostream&gt; using namespace std; class A { int id; public: A (int i) { id = i; } void print () { cout &lt;&lt; id &lt;&lt; endl; } }; int main() { A a[2]; a[0].print(); a[1].print(); return 0; } There is a compilation error in line "A a[2]". There is no d
3 min read
Output of C++ Program | Set 16
Predict the output of following C++ programs. Question 1 #include&lt;iostream&gt; using namespace std; class Base { public: int fun() { cout &lt;&lt; &quot;Base::fun() called&quot;; } int fun(int i) { cout &lt;&lt; &quot;Base::fun(int i) called&quot;; } }; class Derived: public Base { public: int fun(char x) { cout &lt;&lt; &quot;Derived::fun(char
2 min read
Output of C++ Program | Set 18
Predict the output of following C++ programs. Question 1 #include &lt;iostream&gt; using namespace std; template &lt;int N&gt; class A { int arr[N]; public: virtual void fun() { cout &lt;&lt; &quot;A::fun()&quot;; } }; class B : public A&lt;2&gt; { public: void fun() { cout &lt;&lt; &quot;B::fun()&quot;; } }; class C : public B { }; int main() { A
2 min read
Output of C programs | Set 30 (Switch Case)
Prerequisite - Switch Case in C/C++ Interesting Problems of Switch statement in C/C++ Program 1 #include &lt;stdio.h&gt; int main() { int num = 2; switch (num + 2) { case 1: printf(&quot;Case 1: &quot;); case 2: printf(&quot;Case 2: &quot;); case 3: printf(&quot;Case 3: &quot;); default: printf(&quot;Default: &quot;); } return 0; } Output: Default:
2 min read
Output of C++ programs | Set 36
Ques 1. What is the output of the following assuming that the size of int is 4 bytes. #include &lt;iostream&gt; using namespace std; class abc { void f(); void g(); int x; }; main() { cout &lt;&lt; sizeof(abc) &lt;&lt; endl; } Options : A) 12 B) 4 C) 8 D) Compile error Answer : B Explanation : Only the class member variables constitutes as the size
3 min read
Output of C++ programs | Set 37
Predict the output for the following C++ code: Question 1 #include &lt;iostream&gt; int main() { if (std::cout &lt;&lt; &quot;hello&quot;) std::cout &lt;&lt; &quot; world&quot;; else std::cout &lt;&lt; &quot; else part&quot;; return 0; } Output: hello world Description: Since std::cout&lt;&lt;&quot;hello&quot; returns a reference to std::cout, ther
2 min read
Output Iterators in C++
After going through the template definition of various STL algorithms like std::copy, std::move, std::transform, you must have found their template definition consisting of objects of type Output Iterator. So what are they and why are they used ? Output iterators are one of the five main types of iterators present in C++ Standard Library, others be
6 min read
C++ Basic Syntax
C++ is a general-purpose, object-oriented programming language. It was developed in 1979 by Bjarne Stroustrup at AT &amp; T Bell Laboratory. It is a high-level programming language &amp; advanced version of C programming language. As Compared to other programming languages like Java, and Python, it is the fastest programming language. What is Synta
7 min read
Check input character is alphabet, digit or special character
All characters whether alphabet, digit or special character have ASCII value. Input character from the user will determine if it's Alphabet, Number or Special character.ASCII value ranges- For capital alphabets 65 - 90For small alphabets 97 - 122For digits 48 - 57 Examples : Input : 8 Output : Digit Input : E Output : Alphabet C/C++ Code // CPP pro
3 min read
Input an integer array without spaces in C
How to input a large number (a number that cannot be stored even in long long int) without spaces? We need this large number in an integer array such that every array element stores a single digit. Input : 10000000000000000000000000000000000000000000000 We need to read it in an arr[] = {1, 0, 0...., 0} In C scanf(), we can specify count of digits t
2 min read
Find the maximum sum (a+b) for a given input integer N satisfying the given condition
Given an integer N, the task is to find the largest sum (a + b) {1 ? a ? N, 1 ? b ? N} such that a * b/(a + b) is an integer (i.e a + b divides a * b) and a != b. Examples: Input: N = 10 Output: 9 Explanation: The numbers a = 3 and b = 6 leads to sum = 9 also 6 * 3 = 18 which is divisible by 6 + 3 = 9 Input: N = 20 Output: 27 Naive Approach: The id
11 min read
C++ Wait for User Input
Waiting for User input is common functionality in any program requiring some form of user intervention. Whether it is halting the execution to see the output produced, or is it for taking in user input, halting the execution for input is one of the most common tasks that are performed by a program. In this article, you will learn different methods
4 min read
How to Take Input in Array in C++?
Arrays in C++ are derived data types that can contain multiple elements of the same data type. They are generally used when we want to store multiple elements of a particular data type under the same name. We can access different array elements using their index as they are stored sequentially in the memory. We can also assign some value to these e
3 min read
How to use getline() in C++ when there are blank lines in input?
In C++, if we need to read a few sentences from a stream, the generally preferred way is to use the getline() function as it can read string streams till it encounters a newline or sees a delimiter provided by the user. Also, it uses &lt;string.h&gt; header file to be fully functional. Here is a sample program in c++ that reads four sentences and d
2 min read
getchar_unlocked() – Faster Input in C/C++ For Competitive Programming
getchar_unlocked() is similar to getchar() with the exception that it is not thread-safe. This function can be securely used in a multi-threaded program if and only if they are invoked when the invoking thread possesses the (FILE*) object, as is the situation after calling flockfile() or ftrylockfile(). Syntax: int getchar_unlocked(void); Example:
2 min read
Clearing The Input Buffer In C/C++
What is a buffer? A temporary storage area is called a buffer. All standard input and output devices contain an input and output buffer. In standard C/C++, streams are buffered. For example, in the case of standard input, when we press the key on the keyboard, it isn’t sent to your program, instead of that, it is sent to the buffer by the operating
6 min read
Input Iterators in C++
After going through the template definition of various STL algorithms like std::find, std::equal, std::count, you must have found their template definition consisting of objects of type Input Iterator. So what are they and why are they used?Input iterators are one of the five main types of iterators present in the C++ Standard Library, others being
6 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Practice Tags :