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);
name.replace(0, 3, "Augusta");
bool has_prefix = name.starts_with("Aug");

These operations cover a lot of ordinary string work before you need regular expressions or custom parsers.

Input and output

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

Formatted extraction is good for token-oriented input. Use getline when spaces matter.

Line-based input

std::string line;
std::getline(std::cin, line);
std::istringstream input{"42 debug"};
int level{};
std::string tag;
input >> level >> tag;

String streams are useful when you want to parse one line at a time after reading it safely.

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

Practical rule of thumb

Example in practice

#include <vector>

int main() {
    std::vector<int> values{1, 2, 3};
    values.push_back(4);
    return values.back();
}

Try this variation

Reserve space before growth and pass read-only text as `std::string_view`. That introduces both allocation control and borrowing in one small step.

#include <string_view>
#include <vector>

void add_name(std::vector<std::string>& names, std::string_view name) {
    names.emplace_back(name);
}