Getting Inputs in C++

 


In C++, we use cin (Character Input) from the iostream library to take input from the user. It reads values from the keyboard and stores them in variables.


Basic Input Example

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;
    cout << "You are " << age << " years old." << endl;
    return 0;
}

Explanation:

  1. cout << "Enter your age: "; → Displays a prompt for the user.
  2. cin >> age; → Reads an integer from the user and stores it in age.
  3. cout << "You are " << age << " years old." << endl; → Outputs the entered value.

Taking Multiple Inputs

You can take multiple inputs in a single line using cin.

#include <iostream>
using namespace std;

int main() {
    string name;
    int age;

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

    cout << "Hello, " << name << "! You are " << age << " years old." << endl;
    return 0;
}

📌 Note: If the name contains spaces (e.g., "John Doe"), only "John" will be stored.
To handle spaces, use getline().


Using getline() for String Input

If you want to take full-line input (including spaces), use getline().

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

int main() {
    string fullName;

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

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

📌 Important: If getline() is used after cin, add cin.ignore(); before it to clear the input buffer.


Taking Character Input (char)

To take a single character input:

#include <iostream>
using namespace std;

int main() {
    char grade;
    cout << "Enter your grade: ";
    cin >> grade;
    cout << "You got grade: " << grade << endl;
    return 0;
}

Taking Floating-Point Input (double or float)

For decimal values:

#include <iostream>
using namespace std;

int main() {
    double price;
    cout << "Enter the price: ";
    cin >> price;
    cout << "The price is $" << price << endl;
    return 0;
}

Would you like to learn about input validation (handling wrong inputs)? 🚀

Post a Comment

0 Comments