0
0
CppHow-ToBeginner · 3 min read

How to Use cin and cout in C++: Input and Output Basics

In C++, use cin to read input from the keyboard and cout to display output on the screen. Both are part of the iostream library and work with the extraction (>>) and insertion (<<) operators respectively.
📐

Syntax

cin reads input from the user using the extraction operator >>. cout prints output to the screen using the insertion operator <<. Both require including the <iostream> header and using the std namespace or prefix.

  • std::cin >> variable; reads input into variable.
  • std::cout << value; prints value to the screen.
cpp
#include <iostream>

int main() {
    int number;
    std::cout << "Enter a number: ";
    std::cin >> number;
    std::cout << "You entered: " << number << std::endl;
    return 0;
}
💻

Example

This example asks the user to enter their age and then prints it back. It shows how cin and cout work together for input and output.

cpp
#include <iostream>

int main() {
    int age;
    std::cout << "Please enter your age: ";
    std::cin >> age;
    std::cout << "Your age is " << age << "." << std::endl;
    return 0;
}
Output
Please enter your age: 25 Your age is 25.
⚠️

Common Pitfalls

Common mistakes when using cin and cout include:

  • Not including <iostream> or forgetting std:: prefix or using namespace std;.
  • Mixing input types without clearing the input buffer, causing unexpected behavior.
  • Using cin with strings without std::getline, which can cause input to stop at the first space.
cpp
#include <iostream>
#include <string>

int main() {
    std::string name;
    std::cout << "Enter your full name: ";
    // Wrong: std::cin >> name; // stops at first space
    std::getline(std::cin, name); // Correct way to read full line
    std::cout << "Hello, " << name << "!" << std::endl;
    return 0;
}
Output
Enter your full name: John Smith Hello, John Smith!
📊

Quick Reference

Remember these tips when using cin and cout:

  • Always include <iostream>.
  • Use std::cin >> variable; to get input.
  • Use std::cout << value; to print output.
  • Use std::getline(std::cin, stringVariable); to read full lines of text.
  • Use std::endl or \n to add a new line.

Key Takeaways

Use cin with >> to read user input into variables.
Use cout with << to display output on the screen.
Always include <iostream> and use the std namespace or prefix.
Use std::getline to read full lines of text including spaces.
Remember to handle input types carefully to avoid unexpected behavior.