Data Structures & Algorithms Lecture Notes

6 November 2008 • Assignment 1a Code Review


Outline

The Problem

No Prompting

Testing

Tests

Coding

Program Defensively

Fixed-Size Arrays

No Coredumping

Unchecked Input

Know Your Tools

Easy I-O Example

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

  // Read an int from ins and store it in *value.  
  // Return an error message or the empty string 
  // if no errors.

  ins >> *value
  if (ins.eof())
    return "Unexpected eof"
  if (ins.fail())
    return "Unexpected non-integer value"
  if (ins.bad())
    return "Unrecoverable I-O error"

  return ""

A Harder Alternative

bool isNotAnInt(string s)
  bool isNaI = false
  if (s[0] == '-') //if it's a negative number
	  //skip 1st character, goes through chars in string 
	  for (unsigned int k = 1; k < s.length(); k++)
		  //if it's not a # or if it's a decimal
		  if(!(isdigit(s[k])) || s[k] == '.')
			  isNaI = true
  else
	  //goes through chars in string
	  for (unsigned int j = 0; j < s.length(); j++)
		  //if it's not a # or if it's a decimal
		  if (!(isdigit(s[j])) || s[j] == '.')
			  isNaI = true
  return isNaI

int validateWidth(string s)
  int number = atoi(s.c_str())
  if (isNotAnInt(s))
    // error
  else if (!(withinRange(number)))
    // error
  else
    return number

int getWidth()
  string strWidth
  cin >> strWidth
  return validateWidth(strWidth)

Write Small Functions

Comment Functions

Example Function Comments

An Interesting Case

Copying Code

Code Factoring

void perr(const string & emsg)
  cerr << "!!! " < emsg < ".\n"
  exit(EXIT_FAILURE)

perr(string("Row should be non negative, not ") + row)

perr(string("Column should be non negative, not " + col)

perr("Region height should be an integer")

perr(string("Rainfall should be non-negative, not ") + rainfall)


This page last modified on 8 February 2006.

Creative
    Commons License