C++ Program to Print Number Entered by User

Updated on December 20, 2024
Print number entered by user header image

Introduction

When you start learning C++, one of the fundamental tasks is to interact with the user by accepting input and displaying output. A simple and common exercise to achieve this is creating a program that prints a number entered by the user. This type of program helps you understand basic C++ input/output (I/O) operations, which are essential for more complex applications.

In this article, you will learn how to develop a C++ program that prompts a user to enter a number and then prints that number. The discussion includes different methods to enhance user interaction and error handling to ensure the program behaves correctly in different input scenarios.

Basic I/O in C++

Accepting User Input

  1. Include the necessary header files.

  2. Declare the main function.

  3. Initialize the variable to store user input.

  4. Prompt the user to enter a number.

  5. Use cin to capture user input.

  6. Output the number back to the user.

    cpp
    #include <iostream>
    using namespace std;
    
    int main() {
        int userNumber;
        cout << "Please enter a number: ";
        cin >> userNumber;
        cout << "You entered: " << userNumber << endl;
        return 0;
    }
    

    Here, the program includes the <iostream> header, which is essential for C++ input and output streams. The cin object is used for input, and cout is used for output. By prompting the user and then displaying the entered number, you complete a basic I/O cycle.

Validating User Input

  1. Ensure cin successfully reads an integer.

  2. Implement simple error handling.

    cpp
    #include <iostream>
    using namespace std;
    
    int main() {
        int userNumber;
        cout << "Please enter a number: ";
        if (cin >> userNumber) {
            cout << "You entered: " << userNumber << endl;
        } else {
            cout << "Error: Invalid input." << endl;
            cin.clear(); // Clear error flag
            cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Ignore wrong input
        }
        return 0;
    }
    

    This enhanced version checks whether the input operation succeeds. If cin >> userNumber fails (e.g., if the user enters a non-numeric value), the program prints an error message. The cin.clear() function resets the error state of cin, allowing further I/O operations. cin.ignore(...) skips the rest of the incorrect input.

Advanced User Interaction

Using Loops for Continuous Input

  1. Allow the user to enter multiple numbers until a command (like exit) is given.

  2. Utilize a loop to maintain the program running.

    cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        int userNumber;
        string input;
        while (true) {
            cout << "Enter a number or 'exit' to quit: ";
            if (!(cin >> userNumber)) {
                cin.clear();
                cin >> input;
                if (input == "exit") {
                    break;
                } else {
                    cout << "Invalid command or number! Please try again." << endl;
                    cin.ignore(numeric_limits<streamsize>::max(), '\n');
                }
            } else {
                cout << "You entered: " << userNumber << endl;
            }
        }
        cout << "Program ended." << endl;
        return 0;
    }
    

    In this example, the program runs in a continuous loop, processing user inputs. If the user types exit, the loop breaks, and the program terminates. This method enhances user interaction by not requiring the program to be restarted for each input.

Conclusion

Developing a C++ program to print a number entered by the user is an excellent starting point for understanding the basics of I/O in C++. By experimenting with different coding practices outlined here, such as input validation and loop-based continuous input, you foster enhanced user interactions and robust program designs. Integrate these methods into your development practice to build more interactive and error-resistant applications.