C++ 23 cheatsheet
C++ 23: Input, exceptions and threads
7 common C++ 23 tasks.
Read a file line by line
Read a text file with ifstream and getline.
std::ifstream file("data.txt");
std::string line;
while (std::getline(file, line)) {
std::cout << line << '\n';
}
Read a line from the keyboard
Read a whole line, including spaces.
std::string name;
std::getline(std::cin, name);
Handle exceptions
Catch exceptions by const reference.
try {
auto n = std::stoi(text);
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}
Run code on another thread
Start a thread and wait for it. std::jthread joins automatically when it is destroyed (C++20).
std::jthread worker([] { std::cout << "working\n"; });
Compute a value in the background
Run a function asynchronously and collect the result later.
auto fut = std::async(std::launch::async, [] { return 6 * 7; });
std::cout << fut.get() << '\n';
Share a counter between threads
An atomic integer can be updated by several threads without a mutex.
std::atomic<int> hits{0};
++hits;
Time a section of code
Measure elapsed time with a steady clock.
auto start = std::chrono::steady_clock::now();
work();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();