C++ cin
Created By: chatGPT
In C++, cin is used to take input from the standard input stream, which is usually the keyboard. You can use it to read various types of data, such as integers, floating-point numbers, and strings. The basic syntax involves using the insertion operator
>>
to extract the input and store it in a variable.#include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Your age is: " << age << std::endl;
return 0;
}
To read multiple values in a single line, you can chain multiple
cin
statements. Make sure to handle spaces properly, especially when reading strings. For strings, use the std::getline
function if you want to include spaces.#include <iostream>
#include <string>
int main() {
int num;
std::string name;
std::cout << "Enter your name and age: ";
std::cin >> name >> num;
std::cout << "Hello, " << name << ". You are " << num << " years old." << std::endl;
return 0;
}
When using cin, it's crucial to ensure that the input type matches the variable type in your program. If a user enters a value of the wrong type, it can cause the input to fail. You can check for input failures by testing
std::cin.fail()
.#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (std::cin.fail()) {
std::cout << "Invalid input! Please enter a valid number." << std::endl;
// clear the fail state
std::cin.clear();
// discard the invalid input
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} else {
std::cout << "You entered: " << number << std::endl;
}
return 0;
}
To read an entire line including spaces, you can replace the
>>
operator with std::getline()
. This is especially useful when dealing with string inputs that may contain spaces.#include <iostream>
#include <string>
int main() {
std::string fullName;
std::cout << "Enter your full name: ";
std::getline(std::cin, fullName);
std::cout << "Your full name is: " << fullName << std::endl;
return 0;
}