User input with cin function in C++

User input with cin function in C++

The provided C++ code is a simple console application that prompts the user to enter an integer, outputs the entered integer, doubles the entered integer, and then outputs the doubled value.

Code

#include <iostream> // Include the iostream library to enable input/output operations
using namespace std; // Use the standard namespace

// Main function
int main() {
    int userInput; // Declare an integer variable to store user input

    // Prompt the user to enter an integer
    cout << "Enter an integer: ";
    cin >> userInput; // Read the user input from the console

    // Output the entered integer
    cout << "You entered: " << userInput << endl;

    userInput = 2 * userInput; // Double the user input

    // Output the doubled value
    cout << "The doubled value is: " << userInput << endl;

    return 0; // Return 0 to indicate that the program has run successfully
}

Explanation

The provided C++ code is a simple console application that prompts the user to enter an integer, outputs the entered integer, doubles the entered integer, and then outputs the doubled value.

The code begins with the inclusion of the iostream library, which is necessary for input/output operations in C++. The using namespace std; statement is used to avoid having to prefix standard library functions with std::.

#include <iostream>
using namespace std;

The main function is the entry point of the program. Inside this function, an integer variable userInput is declared to store the user’s input.

int main() {
    int userInput;

The program then prompts the user to enter an integer using cout, and reads the user’s input from the console using cin.

cout << "Enter an integer: ";
cin >> userInput;

The entered integer is then outputted to the console.

cout << "You entered: " << userInput << endl;

The userInput variable is then doubled by multiplying it by 2.

userInput = 2 * userInput;

Finally, the doubled value is outputted to the console, and the main function returns 0 to indicate that the program has run successfully.

cout << "The doubled value is: " << userInput << endl;
return 0;

This code is a basic example of user interaction and arithmetic operations in C++.

Output

Enter an integer: 12
You entered: 12
The doubled value is: 24

Process finished with exit code 0
Last updated on