Data Structures & Algorithms, Fall 2008

Programming Assignment 1a - An Example Solution


Table of Contents

Introduction

This page gives a solution to part 1 of the first programming assignment.
<m.cc>=

#include <iostream>
#include <string>
#include <stdlib.h>


// Deja vu c++ style.

  static std::string read_unsigned(std::istream &, unsigned &, const char * const)
  static std::string read_signed(std::istream &, int &, const char * const)


static void
do_err(const std::string & emsg) 

  // If the given error message is non-empty, print it and die.  Otherwise do
  // nothing.

  if not emsg.empty()
    std::cerr << "!!! " << emsg << ".\n"
    exit(EXIT_FAILURE)


int
main() 

  unsigned h, w
  do_err(read_unsigned(std::cin, h, "height"))
  do_err(read_unsigned(std::cin, w, "width"))

  unsigned cnt = h*w
  int * elevations = new int [cnt]
  for unsigned i = 0; i < cnt; i++
    do_err(read_signed(std::cin, elevations[i], "elevation"))

  unsigned rainfall
  do_err(read_unsigned(std::cin, rainfall, "rainfall"))

  delete [] elevations


static std::string
read_signed(std::istream & ins, int & value, const char * const what) 

  // Read an int from the given input stream; store the value read in the
  // given pointer.  Return true if no errors occurred, false otherwise.

  ins >> value
  if ins.eof()
    return std::string("Unexpected eof; ") + what + " expected"
  if ins.fail()
    return std::string("Unexpected value; integer ") + what + " expected"
  if ins.bad()
    return std::string("Unrecoverable I-O error occurred during ") + what + " read"
                      
  return ""


static std::string
read_unsigned(std::istream & ins, unsigned & value, const char * const what) 

  // Read an int from the given input stream; store the value read in the
  // given pointer.  Return true if no errors occurred, false otherwise.

  // This code isn't correct: the largest unsigned value is too large to fit in
  // a signed integer.  The fix is to read into a double-sized signed, check
  // the size, and then cast down to a single-sized unsigned if appropriate.
  // Consider it done.

  int i
  std::string emsg = read_signed(ins, i, what)
  if not emsg.empty()
    return emsg

  if i < 0
    return std::string("Negative ") + what + " value read, non-negative value expected"

  value = static_cast<unsigned>(i)

  return ""
Defines m.cc (links are to index).

This code is written to a file (or else not used).

Index


This page last modified on 6 November 2008.

Creative
    Commons License