Strings and I/O

Strings and I/O

String handling, streams, formatting, parsing, and common input/output patterns.

Strings and I/O

String types

Common operations

std::string name = "Ada";
name += " Lovelace";
auto pos = name.find("Love");
auto sub = name.substr(0, 3);

Input and output

int age{};
std::cout << "Enter age: ";
std::cin >> age;
std::cout << "Age = " << age << '\n';

Line-based input

std::string line;
std::getline(std::cin, line);

Safer text parameters

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

Modern formatting

If available, prefer std::format over manual stream concatenation for complex output.

Best-practice reminders

std::string_view pitfalls

std::string_view bad_view() {
    return std::string{"temporary"};
}

Never return or store a view into a temporary string.

Modern formatting

auto text = std::format("{} scored {:.1f}%", name, percent);
std::print("Result: {}\n", text);

Parsing advice