Strings and I/O
Strings and I/O
String handling, streams, formatting, parsing, and common input/output patterns.
Strings and I/O
String handling, streams, formatting, parsing, and common input/output patterns.
std::string: owning text bufferstd::string_view: non-owning view into textstd::ostringstream, std::istringstream: stream-based formatting and parsingstd::string name = "Ada";
name += " Lovelace";
auto pos = name.find("Love");
auto sub = name.substr(0, 3);
int age{};
std::cout << "Enter age: ";
std::cin >> age;
std::cout << "Age = " << age << '\n';
std::string line;
std::getline(std::cin, line);
void greet(std::string_view name) {
std::cout << "Hello, " << name << '\n';
}
If available, prefer std::format over manual stream concatenation for complex output.
std::getline() when spaces matter.std::string_view only when the referenced data outlives the view.operator>> with std::getline().std::string_view pitfallsstd::string_view bad_view() {
return std::string{"temporary"};
}
Never return or store a view into a temporary string.
auto text = std::format("{} scored {:.1f}%", name, percent);
std::print("Result: {}\n", text);
std::format builds strings with Python-style format fields.std::print writes directly to standard output in C++23.std::from_chars for fast numeric parsing in low-level code.std::getline plus parsing when you need robust line-oriented input.