Home C++ A cin tutorial with code examples

A cin tutorial with code examples

In C++, cin is an object of the istream class and is used to take input from the standard input device, typically the keyboard.

The cin object reads input from the user and stores it in variables, allowing interactive programs to process user-provided data.

Basic Syntax of cin

cin >> variable;
  • The >> operator, known as the extraction operator, reads data from the input buffer into the variable.
  • cin skips whitespace characters (like spaces, tabs, and newlines) between inputs automatically.

Let’s explore cin with several examples covering various input scenarios.

1. Basic Input Using cin

A basic example where cin takes an integer as input and displays it.

#include <iostream>
using namespace std;

int main() {
    int age;

    cout << "Enter your age: ";
    cin >> age; // Takes input from the user

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

Explanation:

  • cin >> age; takes an integer input from the user and stores it in age.
  • The input value is then displayed back using cout.

Sample Output:

Enter your age: 25
You entered age: 25

2. Taking Multiple Inputs in One Line

You can take multiple inputs in a single line by chaining cin with the >> operator.

#include <iostream>
using namespace std;

int main() {
    int x, y;

    cout << "Enter two integers separated by space: ";
    cin >> x >> y;

    cout << "You entered x: " << x << " and y: " << y << endl;
    return 0;
}

Explanation:

  • cin >> x >> y; reads two integers separated by whitespace in a single input line.

Sample Output:

Enter two integers separated by space: 10 20
You entered x: 10 and y: 20

3. Taking String Input

To read a single word, you can use cin with a string variable. cin stops reading when it encounters whitespace (space, tab, newline).

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

int main() {
    string name;

    cout << "Enter your first name: ";
    cin >> name; // Reads a single word

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

Explanation:

  • cin reads a single word into the name variable. It stops at the first whitespace character.

Sample Output:

Enter your first name: Alice
Hello, Alice!

4. Using getline with cin to Read a Full Line

For multi-word input (like full names or sentences), getline is used with cin.

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

int main() {
    string fullName;

    cout << "Enter your full name: ";
    cin.ignore(); // Clear any leftover input (useful if used after cin >>)
    getline(cin, fullName); // Reads an entire line

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

Explanation:

  • getline(cin, fullName); reads the entire line including spaces until the newline character.
  • cin.ignore(); clears any leftover input in the buffer, especially if getline follows a cin >>.

Sample Output:

Enter your full name: Alice Johnson
Hello, Alice Johnson!

5. Handling Multiple Data Types with cin

You can input variables of different data types in one statement by chaining cin with the extraction operator.

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

int main() {
    string name;
    int age;
    double height;

    cout << "Enter your name, age, and height (in cm): ";
    cin >> name >> age >> height;

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

Explanation:

  • cin >> name >> age >> height; reads input for a string, int, and double variable, separated by whitespace.

Sample Output:

Enter your name, age, and height (in cm): Alice 25 167.5
Name: Alice, Age: 25, Height: 167.5 cm

6. Using cin with Mathematical Operations

cin allows input directly into expressions to perform operations on user input.

#include <iostream>
using namespace std;

int main() {
    int a, b;

    cout << "Enter two integers: ";
    cin >> a >> b;

    cout << "Sum: " << a + b << endl;
    cout << "Difference: " << a - b << endl;
    cout << "Product: " << a * b << endl;
    cout << "Quotient: " << a / b << endl;

    return 0;
}

Explanation:

  • cin takes two integers and performs mathematical operations like addition, subtraction, multiplication, and division.

Sample Output:

Enter two integers: 10 2
Sum: 12
Difference: 8
Product: 20
Quotient: 5

7. Checking for Successful Input with cin

You can check if cin was able to read valid input data using conditional statements and cin.fail().

#include <iostream>
using namespace std;

int main() {
    int number;

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

    if (cin.fail()) {
        cout << "Invalid input. Please enter an integer." << endl;
    } else {
        cout << "You entered: " << number << endl;
    }

    return 0;
}

Explanation:

  • cin.fail() returns true if the input was invalid for the variable’s data type (e.g., entering a character instead of an integer).

Sample Output:

Enter an integer: abc
Invalid input. Please enter an integer.

8. Clearing the cin Error State and Input Buffer

If an error occurs (e.g., entering invalid data), you can clear the cin error state and ignore remaining input in the buffer to allow re-entry.

#include <iostream>
using namespace std;

int main() {
    int number;

    while (true) {
        cout << "Enter an integer: ";
        cin >> number;

        if (cin.fail()) {
            cout << "Invalid input. Please enter an integer." << endl;
            cin.clear();            // Clear the error state
            cin.ignore(1000, '\n');  // Discard invalid input
        } else {
            cout << "You entered: " << number << endl;
            break;
        }
    }
    return 0;
}

Explanation:

  • cin.clear() resets the error state so cin can be used again.
  • cin.ignore(1000, ‘\n'); discards remaining characters in the input buffer up to 1000 characters or until a newline is found.

Sample Output:

Enter an integer: abc
Invalid input. Please enter an integer.
Enter an integer: 42
You entered: 42

9. cin in a Loop to Continuously Take Input

Using cin in a loop allows repeated input processing, such as reading multiple values.

#include <iostream>
using namespace std;

int main() {
    int number, sum = 0;

    cout << "Enter integers to sum (enter 0 to stop): ";
    while (cin >> number && number != 0) {
        sum += number;
    }

    cout << "Total sum: " << sum << endl;
    return 0;
}

Explanation:

  • The loop continues to take input until 0 is entered.
  • Each entered number (other than 0) is added to sum.

Sample Output:

Enter integers to sum (enter 0 to stop): 5 10 15 0
Total sum: 30

10. Using cin with Arrays

You can use cin to take multiple inputs and store them in an array.

#include <iostream>
using namespace std;

int main() {
    int numbers[5];

    cout << "Enter 5 integers: ";
    for (int i = 0; i < 5; i++) {
        cin >> numbers[i];
    }

    cout << "You entered: ";
    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << " ";
    }
    cout << endl;

    return 0;
}

Explanation:

  • The for loop takes 5 integers and stores each in an array element.
  • Another for loop is used to display the entered values.

Sample Output:

Enter 5 integers: 1 2 3 4 5
You entered: 1 2 3 4 5

Summary Table

Use Case Code Example Description
Basic Input cin >> variable; Reads a single variable from input
Multiple Inputs cin >> x >> y; Takes multiple inputs in one line
Single Word String Input cin >> name; Reads a single word (up to whitespace) into a string variable
Multi-Word String with getline getline(cin, str); Reads a full line including spaces
Mixed Data Types cin >> name >> age >> salary; Takes inputs of different data types in one line
Checking Valid Input if (cin.fail()) { … } Checks if cin successfully reads a valid input
Clearing Error State cin.clear(); cin.ignore(…); Clears error and ignores remaining input
Continuous Input Loop while (cin >> number && number != 0) Continues reading input until a condition is met
Array Input for (int i = 0; i < n; i++) { cin >> arr[i]; } Stores input in array elements

Complete Example

This example combines several concepts to create a program that takes and validates multiple types of user input.

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

int main() {
    int age;
    double height;
    string name;

    cout << "Enter your name: ";
    cin.ignore(); // Ignore any newline left in the input buffer
    getline(cin, name);

    cout << "Enter your age: ";
    while (!(cin >> age)) { // Loop until a valid integer is entered
        cout << "Invalid input. Please enter an integer for age: ";
        cin.clear();
        cin.ignore(1000, '\n');
    }

    cout << "Enter your height (in cm): ";
    while (!(cin >> height)) { // Loop until a valid double is entered
        cout << "Invalid input. Please enter a number for height: ";
        cin.clear();
        cin.ignore(1000, '\n');
    }

    cout << "\n--- User Information ---" << endl;
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Height: " << height << " cm" << endl;

    return 0;
}

Sample Output:

Enter your name: Alice Johnson
Enter your age: twenty
Invalid input. Please enter an integer for age: 25
Enter your height (in cm): 167.5

--- User Information ---
Name: Alice Johnson
Age: 25
Height: 167.5 cm

Key Takeaways

  • cin provides an easy way to handle interactive input in C++.
  • Using cin with error handling helps in creating robust programs by managing unexpected or invalid inputs.
  • Combining getline with cin.ignore can handle multi-word strings effectively.

You may also like