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:
- We use the
doubledata type to allow the user to input both integers and floating-point numbers. std::coutis used to display a prompt to the user.std::cinis used to capture the user’s input. The user’s input will be stored in thenumbervariable.- We then print out the number the user entered with
std::cout.
To run the program:
- Save it in a file, say
print_number.cpp. - Compile the program with:
g++ print_number.cpp -o print_number
- 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.
