Handling User Input in C++
In C++, user input is handled using the std::cin
object along with the extraction operator >>
. This allows programs to receive input from the user via the console.
Key Topics
Using std::cin
The std::cin
object is used to receive input from the user. It works with fundamental data types like integers, floats, characters, etc.
Example: Receiving an Integer Input
#include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Your age is " << age << std::endl;
return 0;
}
Output:
Enter your age: 25
Your age is 25
Explanation: The program prompts the user to enter their age. The input is stored in the variable age
and then displayed back to the user.
Key Takeaways
std::cin
is used for user input in C++.- The extraction operator
>>
reads input from the console. - Ensure the data type of the variable matches the expected input.
Input with Different Data Types
You can receive input of various data types using std::cin
. It's important to declare the variable with the correct data type.
Example: Receiving Multiple Inputs
#include <iostream>
int main() {
int age;
double salary;
char grade;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Enter your salary: ";
std::cin >> salary;
std::cout << "Enter your grade: ";
std::cin >> grade;
std::cout << "Age: " << age << ", Salary: " << salary << ", Grade: " << grade << std::endl;
return 0;
}
Output:
Enter your age: 28
Enter your salary: 50000.50
Enter your grade: A
Age: 28, Salary: 50000.5, Grade: A
Explanation: The program receives inputs of different data types and displays them. It demonstrates how std::cin
can handle multiple inputs sequentially.
Key Takeaways
- Declare variables with the appropriate data types for the expected input.
- Order of input matters when using
std::cin
sequentially. - Be cautious of input buffer issues when mixing data types.
Using getline() for Strings
To read a full line of text, including spaces, use the std::getline()
function.
Example: Receiving a String Input
#include <iostream>
#include <string>
int main() {
std::string fullName;
std::cout << "Enter your full name: ";
std::getline(std::cin, fullName);
std::cout << "Hello, " << fullName << "!" << std::endl;
return 0;
}
Output:
Enter your full name: Durai Vijayakanth
Hello, Durai Vijayakanth!
Explanation: std::getline()
reads an entire line from the input buffer, allowing the user to input strings that contain spaces.
Key Takeaways
- Use
std::getline()
to read strings with spaces. - Include the
<string>
header when working withstd::string
. - Be aware of input buffer issues when mixing
std::cin
andstd::getline()
.