Lecture Notes for Advanced Programming II

28 March 2002 - A Thrice-Made Error


Three Stream I-O Problems


The First Program

int main() {

  string line
  strvec bloc
  int block_changed = 0

  while true
    bloc.clear()
    while true
      getline(cin, line)
      if !cin.good()
        return 0
      if line.length() > 0
	bloc.push_back(line)
      else
       break

    if block.size() > 0
      do
	cons_fold(bloc)
	eval_bloc(bloc, block_changed)
      while block_changed == 1
      print(bloc)


What Went Wrong?


What's the Fix?


The First Program Reconfigured

int main() {

  string line
  strvec bloc

  while true
    bloc.clear()
    while true
      getline(cin, line)
      if cin.good() and line.length() > 0
	bloc.push_back(line)
      else
       break

    if block.size() == 0
      break

    do cons_fold(bloc)
    while eval_bloc(bloc)
    print(bloc)


The Second Program

int main()

  vector<A> av
  string line

  while(true)
    getline(cin, line)
    if cin.eof() break

    if line != ""
      A ab
      ab.expression = line
      ab.get_elements()

      if !ab.isvalid()
	cerr << "Input errors\n"
	exit(1)

      av.push_back(ab)

    else
      E_Optimization(av)
      av.clear()


What Went Wrong?


How to Fix


The Second Program Reconfigured

int main()

  vector<A> av
  string line

  while true
    vector<string> input
    while getline(cin, line) and (line != "")
      input.push_back(line)
    if input.empty()
      break
    if check(input, av)
      E_Optimization(av)

bool check(input, av) 
  av.clear()
  for each l line in input
    A ab
    ab.expression = l
    ab.get_elements()
    if !ab.isvalid()
      return false
    av.push_back(ab)
  return true


The Third Program


int main()

  vector<string> outputVect
  vector <Code_line> cVect
  bool errorFlag = false

  while getline(cin, str)
    if s.empty()
      if !cVect.empty()
	if !errorFlag
	  process_block(cVect, outputVect)
      if errorFlag
	outputVect.push_back(error)
      errorFlag = false
    else if !errorFlag
      Code_line cln
      if process_line (s, cln)
	cVect.push_back(cln)
      else
	errorFlag = true

  if cin.eof()
    if !cVect.empty()
      if !errorFlag
	process_block(cVect, outputVect)
      else
	outputVect.push_back(emsg)
      
  for (i = 0; i < outputVect.size(); i++)
    cout << outputVect[i]


What Went Wrong?


How to Fix?


The Third Program Reconfigured

int main()

  vector<string> outputVect

  do
    vector <Code_line> cVect
    while getline(cin, s) and !s.empty()
      Code_line cln
      if process_line (s, cln)
	cVect.push_back(cln)
      else
	cVect.push_back(error_message)

    if !cVect.empty()
      process_block(cVect, outputVect)
  while !cin.eof()

  for (i = 0; i < outputVect.size(); i++)
    cout << outputVect[i]


Points to Remember


This page last modified on 25 April 2002.