C++ strings and string streams

std::string manages its own memory and grows as needed. size gives the length, substr extracts part of the text, and find returns the position of a match or std::string::npos if there is none. Unlike a C string, it needs no terminating zero handling and is safe to copy and concatenate.

C++
#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::string text = "Programonic is fun";
  std::cout << text.size() << " " << text.substr(0, 7) << " " << text.find("is") << "\n";

  std::istringstream input("alpha 3\nbeta 5\ngamma x\n");
  std::string line;
  int total = 0;
  while (std::getline(input, line)) {
    std::istringstream fields(line);
    std::string name;
    int value;
    if (fields >> name >> value) {
      std::cout << name << "=" << value << "\n";
      total += value;
    } else {
      std::cout << "bad line: " << line << "\n";
    }
  }
  std::cout << "total " << total << "\n";
  std::cout << std::to_string(42) + "!" << " " << std::stoi("123") + 1 << "\n";
}
Read the full lesson