Read from console in C++

Wed 01 January 2020
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main() {
  // read 2 integers, seperated by space
  int a, b;
  cout << "Enter 2 integers, seperated by space: ";
  cin >> a >> b;
  cout << "a: " << a << ", b: " << b << endl;

  // read single word c-style string.
  // NB: May not contain spaces.
  char season[20];
  cout << "Enter your favorite season: ";
  cin >> season;
  cout << endl;

  // ignore newline chars left by cin
  // TLDR: cin discards any separators that come before the sequence you
  // intend to read. Any separators after, including line breaks, are kept
  // in the input buffer.
  cin.ignore();

  string name;
  cout << "Please, enter your full name: ";
  getline (cin, name);
  cout << "Hello, " << name << "!" << endl;

  // get multiple strings, split by '-'
  cout << "Enter multiple strings, seperated by '-'." << endl;
  string s, t;
  getline(cin, s);
  stringstream x(s);
  while(getline(x, t, '-')) {
    cout << t << endl;
  }

  // read `n` integers seperated by space, into vector `v`
  int n;
  cin >> n;
  vector<int> v(n);
  for (int i = 0; i < n; ++i) {
    cin >> v[i];
  }
}

Category: Snippets [C++]