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);
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.
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.
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.
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.>>getlinestd::format or std::printstd::from_chars#include <vector>
int main() {
std::vector<int> values{1, 2, 3};
values.push_back(4);
return values.back();
}
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);
}