Types, Variables, and I/O

Types, Variables, and I/O

Learn how data is stored, initialized, and printed in small C++ programs.

Types, Variables, and I/O

Variables

int count = 3;
double price = 9.99;
bool ready = true;
char grade = 'A';
std::string name = "Ada";

Initialization style

Prefer brace initialization when practical:

int age{42};
double ratio{0.5};

Output

std::cout << name << " has age " << age << '\n';

Input

int year{};
std::cin >> year;

Formatted extraction with >> works well for token-style input such as numbers or single words, but it stops at whitespace.

Example program

#include <iostream>
#include <string>

int main() {
    std::string name;
    int age{};

    std::cout << "Name: ";
    std::getline(std::cin, name);
    std::cout << "Age: ";
    std::cin >> age;

    std::cout << name << " will be " << age + 1 << " next year.\n";
}

Input validation pattern

int age{};
if (!(std::cin >> age)) {
    std::cerr << "expected an integer\n";
    return 1;
}

Always validate input before using it. Stream extraction can fail because of unexpected text, overflow, or an earlier stream error.

Mixing >> and getline

int id{};
std::string name;

std::cin >> id;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, name);

If you forget to consume the leftover newline after >>, the next getline will often read an empty line.

Practice ideas

Type deduction and const

const auto max_retries = 3;
auto price = 19.99;

Use const by default for local values that should not change. Use auto when the initializer already makes the type obvious.

Stream state matters

Streams remember whether the last operation succeeded.

if (!std::cin) {
    std::cerr << "input failed\n";
}

Once a stream enters a failed state, later extractions will usually fail too until you clear or replace the stream.

Numeric conversion caution

double price = 9.99;
int whole = static_cast<int>(price);

This drops the fractional part. Conversions between numeric types are common and often intentional, but they should be explicit when information might be lost.

Output formatting basics

std::cout << std::fixed << std::setprecision(2) << price << '\n';

Formatting manipulators are useful when output should be predictable for users, logs, or reports.

Safer modern text APIs

void greet(std::string_view name) {
    std::cout << "Hello, " << name << '\n';
}

std::string_view avoids copies for read-only text parameters, but it does not own data. The caller must keep the underlying string alive.

Input pitfalls

If you mix std::cin >> value with std::getline, consume the leftover newline first or structure input as full lines and parse afterwards.

Small realistic example

#include <iostream>
#include <limits>
#include <string>

int main() {
    int quantity{};
    double price{};
    std::string label;

    std::cout << "Quantity: ";
    if (!(std::cin >> quantity)) {
        return 1;
    }

    std::cout << "Price: ";
    if (!(std::cin >> price)) {
        return 1;
    }

    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Label: ";
    std::getline(std::cin, label);

    std::cout << label << ": " << quantity * price << '\n';
}

This combines numeric input, line input, validation, and formatted output in one small program.

Practical habit

For beginner programs, prefer a simple pattern:

  1. read input
  2. check stream state
  3. compute
  4. print clearly formatted output

That habit scales much better than reading everything first and only checking errors after the fact.

Example in practice

#include <iostream>
#include <string>

int main() {
    std::string name{"Ada"};
    int age{36};
    std::cout << name << " is " << age << "\n";
}

Try this variation

Switch from token-based input to line-based input, then parse the line yourself. This is the first practical step toward robust CLI tools.

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string line{"Ada 36"};
    std::istringstream input{line};
    std::string name;
    int age{};
    input >> name >> age;
}