Lesson 3 of 20Getting Started15 min

Input and Output

Interactive programs receive information from the user and then display a result. C++ commonly uses cin for simple input, getline() for a complete line of text, and cout for output.

Reading Simple Values

Input with cin
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string name;
    int age;

    cout << "Enter your first name: ";
    cin >> name;

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

    cout << "Hello, " << name << ". You are "
         << age << " years old." << endl;

    return 0;
}

Reading Text That Contains Spaces

cin >> normally stops at the first space. Use getline() when the user may enter a full name, address, or sentence.

Input with getline
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string fullName;

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

    cout << "Welcome, " << fullName << "!" << endl;
    return 0;
}
Input tip

When getline() follows cin >>, you may need cin.ignore() to remove the leftover newline character.

Practice task

Ask the user for a full name and favourite programming language, then display both values in one sentence.

Lesson Summary

Read user input with cin and getline, then display clear output with cout.