https://rentry.org/PPP2_p395

// Code derived from Stroustrup's PPP2 book
// § 11.5 Line-oriented input
//  -and beginning on p 395

#include <fstream>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

// clears the cin stream for clean reuse
void clear_cin()
{
  cin.clear();
  cin.ignore(numeric_limits<streamsize>::max(), '\n');  // to end-of-line
}

//------------------------------------------------------------------------------

int main()
{
  {
    //---
    cout << "\n>  ";

    string name;
    cin >> name;           // input: Dennis Ritchie
    cout << name << '\n';  // output: Dennis

    clear_cin();
  }

  {
    //---
    cout << "\n>  ";

    string name;
    getline(cin, name);    // input: Dennis Ritchie
    cout << name << '\n';  // output: Dennis Ritchie
  }

  {
    //---
    cout << '\n';

    string const name{"Dennis Ritchie"};
    string       first_name;
    string       second_name;
    stringstream ss{name};
    ss >> first_name;   // input Dennis
    ss >> second_name;  // input Ritchie

    cout << first_name << ' ' << second_name << '\n';  // output: Dennis Ritchie
  }

  {
    //---
    cout << "\n>  ";

    string command;
    getline(cin, command);  // read the line

    stringstream   ss{command};
    vector<string> words;
    for (string s; ss >> s;)
      words.push_back(s);  // extract the individual words

    for (auto const& word : words)
      cout << word << '\n';
  }
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_11/main_p395.cpp && ./a.out

PrevUpNext

Edit
Pub: 09 Apr 2023 05:57 UTC
Edit: 03 May 2023 10:33 UTC
Views: 595