Get string from file

Monday, August 3rd, 2009

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  FILE *fp;
  char str[128];

  if((fp = fopen(argv[ 1 ], "r"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }

  while(!feof(fp)) {
    if(fgets(str, 126, fp)) 
        printf("%s", str);
  }

  fclose(fp);

  return 0;
}

           
       

Use the greater function object in Map

Sunday, July 26th, 2009

#include <iostream>
#include <map>
#include <functional>
#include <string>
using namespace std;

int main()
{
  map<string, int, greater<string> > mapObject;

  mapObject["A"] = 20;
  mapObject["B"] = 19;
  mapObject["C"] = 10;

  map<string, int, greater<string> >::iterator p;
  
  for(p = mapObject.begin(); p != mapObject.end(); p++) {
    cout << p->first << " has value of ";
    cout << p->second << endl;
  }

  return 0;
}

           
       

Use array to initialize a set

Sunday, July 26th, 2009

 
 

#include <iostream>
using std::cout;
using std::endl;

#include <set>

#include <algorithm>
#include <iterator> // ostream_iterator

int main()
{
   double a[ 5 ] = { 2.1, 4.2, 9.5, 2.1, 3.7 };
   std::set< double, std::less< double > > doubleSet( a, a + 5 );;
   std::ostream_iterator< double > output( cout, " " );

   cout << "doubleSet contains: ";
   std::copy( doubleSet.begin(), doubleSet.end(), output );

   cout << endl;
   return 0;
}

/* 
doubleSet contains: 2.1 3.7 4.2 9.5

 */        
  

cout: how to display float number, ios::showpoint, ios::showpos

Sunday, July 26th, 2009

#include <iostream>
using namespace std;

int main()
{
  cout.setf(ios::showpoint);
  cout.setf(ios::showpos);

  cout << 100.0; 

  return 0;
}

           
       

Overload ostream and istream

Sunday, July 26th, 2009

#include <iostream>
#include <cstring>
using namespace std;

class inventory {
  char item[40];              // name of item
  int onhand;                 // number on hand
  double cost;                // cost of item
public:
  inventory(char *i, int o, double c)
  {
    strcpy(item, i);
    onhand = o;
    cost = c;
  }
  friend ostream &operator<<(ostream &stream, inventory ob);
  friend istream &operator>>(istream &stream, inventory &ob);
};

ostream &operator<<(ostream &stream, inventory ob)
{
  stream << ob.item << ": " << ob.onhand;
  stream << " on hand at $" << ob.cost << ‘\n’;

  return stream;
}

istream &operator>>(istream &stream, inventory &ob)
{
  cout << "Enter item name: ";
  stream >> ob.item;
  cout << "Enter number on hand: ";
  stream >> ob.onhand;
  cout << "Enter cost: ";
  stream >> ob.cost;

  return stream;
}

int main()
{
  inventory ob("hammer", 4, 12.55);

  cout << ob;

  cin >> ob;

  cout << ob;

  return 0;
}