Get Input From User in C++


The standard input by default is the keyboard, and the C++ stream object defined to access it is cin. You have already learned that cout is used to output (print) values. Now we will use cin to get user input. cin is a predefined variable that reads data from user input.

This is a C++ program that prompts the user to enter a number, reads the number from the console, and then prints the number back to the console.

  • The program starts with the line #include<iostream> which is a preprocessor directive that tells the compiler to include the standard input/output library that provides functions to read from and write to the console.
  • The line using namespace std; is a using declaration that allows us to use the standard namespace in our code. This means that we can use functions and objects from the standard library without having to prefix them with std::.
  • The int main() function is the starting point of every C++ program. It returns an integer value to the operating system when the program terminates. In this case, it returns 0 which indicates that the program terminated successfully.
  • The next line int x; declares an integer variable called x.
  • The line cout<<"\nEnter a number: "; uses the cout object from the standard library to print the message "Enter a number: " to the console.
  • The line cin>>x; uses the cin object from the standard library to read a number from the console and store it in the variable x.
  • The line cout<<"\nNumber is: "<<x; uses the cout object from the standard library to print the message "Number is: " followed by the value of x to the console.
  • Finally, the program ends with the return 0; statement which returns 0 to the operating system.

Source Code

#include<iostream>
using namespace std;
int main()
{
    int x;
    cout<<"\nEnter a number: ";
    cin>>x;
    cout<<"\nNumber is: "<<x;
    return 0;
}
To download raw file Click Here

Output

Enter a number: 45
Number is: 45

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples