In C++, user input is taken using the cin object, which reads data from the standard input (usually the keyboard).
cin to Take Input
The extraction operator >> is used with cin to read input and store it in a variable.
#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.
You can take multiple inputs in one line by chaining the >> operator.
#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;
}
To take a single word string, use cin as usual. For multi-word strings, use getline().
#include <iostream>
using namespace std;
int main() {
string name;
cout << "Enter your first name: ";
cin >> name;
cout << "Hello, " << name << "!" << endl;
return 0;
}
#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;
}
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().
#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;
}
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!