CPP Tutorial



C++ USER INPUT


User Input in C++

In C++, user input is taken using the cin object, which reads data from the standard input (usually the keyboard).


Using cin to Take Input

The extraction operator >> is used with cin to read input and store it in a variable.

Example: Taking Integer Input

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;  // Read integer input

    cout << "You entered: " << age << endl;
    return 0;
}
  

When this program runs, it waits for you to enter a number, which is then stored in the variable age.


Taking Multiple Inputs

You can take multiple inputs in one line by chaining the >> operator.

Example:

#include <iostream>
using namespace std;

int main() {
    int a, b;
    cout << "Enter two numbers separated by space: ";
    cin >> a >> b;

    cout << "Sum = " << (a + b) << endl;
    return 0;
}
  

Taking String Input

To take a single word string, use cin as usual. For multi-word strings, use getline().

Example: Single Word

#include <iostream>
using namespace std;

int main() {
    string name;
    cout << "Enter your first name: ";
    cin >> name;

    cout << "Hello, " << name << "!" << endl;
    return 0;
}
  

Example: Multi-word String

#include <iostream>
#include <string>
using namespace std;

int main() {
    string fullName;
    cout << "Enter your full name: ";
    getline(cin, fullName);  // Read full line including spaces

    cout << "Welcome, " << fullName << "!" << endl;
    return 0;
}
  

Note on getline() and cin Mixing

When using getline() after cin, sometimes it skips input due to leftover newline characters in the input buffer. To fix this, use cin.ignore() before getline().

Example Fix:

#include <iostream>
#include <string>
using namespace std;

int main() {
    int age;
    string name;

    cout << "Enter your age: ";
    cin >> age;

    cin.ignore();  // Clear newline from input buffer

    cout << "Enter your full name: ";
    getline(cin, name);

    cout << "Age: " << age << ", Name: " << name << endl;
    return 0;
}
  

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review