C/C++ Programming Pearls

  Often times it can be convenient to get input directly from the command line. Or, if not found at the command line, prompt for input. Prompt messages have been removed from this program. Notice how the input is can accept input from either cin or argv[1].

cmdStrIpt.cc
/*
  program: cmdStrIpt.cc
  
  This program reads from the command string, if
  there is an argv[1] string, otherwite, it
  reads from the input stream.

  So, the following is equivalent:
 
  $cmdStrIpt "sampledata"   

  $cmdStrIpt
    "sampleData"

*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
istream* is;
int main (int argc, char *argv[])
{
  char c;
  string s;
  switch(argc) {
  case 1:
    is = &cin;
    break;
  case 2:
    is = new istringstream(argv[1]);
    break;
  default:
    cerr << " usage: cmdStrIp  <input>  " << endl;
    return 1;
  }


      *is >> s;
      cout << s << endl ;

      if (is != &cin) delete is;


}

*
  Easy way to read in a file.

freq.cc
#include <string>
#include <fstream>
#include <iterator>
#include <sstream>
#include <map>
#include <iostream>
#include <algorithm>

using namespace std;

map < string, int >freq;

void
record (const string & s)
{
  freq[s]++;
}

void
print (const pair < const string, int >&r)
{
  cout << r.first << ' ' << r.second << '\n';
}

int
main (int argc, char **argv)
{
  string infile;

  if (argc == 2)
    {
      infile = argv[1];
    }
  else
    {
      cout << "need filename" << endl;
      return 1;
    }

  ifstream is (infile.c_str ());
  istream_iterator < string > ii (is);
  istream_iterator < string > eos;


  for_each (ii, eos, record);
  for_each (freq.begin (), freq.end (), print);
}

 
SourceForge.net Logo