C++ User Input

In C++, you can take user input using the cin object, which is part of the iostream library.

Example: how to take input from the user


#include <iostream>
using namespace std;

int main() {

    string name;

    // Asking for the user's name
    cout << "Enter your name: ";
    cin >> name; // Taking input for the name

    // Displaying the collected information
    cout << "Hello, " << name  << endl;

    return 0;
}

Explanation:

  • cin is used to take input from the user.
  • cout is used to output information to the screen.

Output:

Enter your name: John
Hello, John

Example: enter your age


#include <iostream>
using namespace std;

int main() {

    int age;

    // Asking for the user's age
    cout << "Enter your age: ";
    cin >> age; // Taking input for the age

    // Displaying the collected information
    cout << "Your age is " << age  << endl;

    return 0;
}

Output:

Enter your age: 35
Your age is 35

C++ User Input – Questions and Answers

Q 1: Which object is used for input?

Ans: cin

Q 2: Which header file supports input?

Ans: <iostream>

Q 3: What operator is used with cin?

Ans: >>

Q 4: Can cin read multiple values?

Ans: Yes.

Q 5: How to input a string?

Ans: Using cin or getline().

C++ User Input – Objective Questions (MCQs)

Q1. Which object is used to take input from the user in C++?






Q2. What header file must be included to use cin in C++?






Q3. Which operator is used with cin to take input in C++?






Q4. What will the following C++ code do?

int age;
cin >> age;






Q5. Which of the following statements correctly takes two integer inputs from the user?






Related C++ User Input Topics