Programs

C++ Program to Print Number Entered by User

Below is a simple C++ program that prompts the user to enter a number, then prints that number:

#include <iostream>

int main() {
    double number;  // We're using 'double' to allow both integer and floating point numbers

    // Prompting the user
    std::cout << "Please enter a number: ";

    // Getting input from the user
    std::cin >> number;

    // Printing the entered number
    std::cout << "You entered: " << number << std::endl;

    return 0;
}

Here’s a brief rundown of the program:

  1. We use the double data type to allow the user to input both integers and floating-point numbers.
  2. std::cout is used to display a prompt to the user.
  3. std::cin is used to capture the user’s input. The user’s input will be stored in the number variable.
  4. We then print out the number the user entered with std::cout.

To run the program:

  1. Save it in a file, say print_number.cpp.
  2. Compile the program with:
g++ print_number.cpp -o print_number
  1. Run the compiled program:
./print_number

You will then be prompted to enter a number. After entering the number, the program will print the number you’ve entered.