This program is supposed to read a lot of strings typed by ...



ONE

This program is supposed to read a lot of strings typed by the user, storing them in an array of exactly the right size. It is then supposed to sort the array (by repeatedly finding the string that should be at the end, and moving it there), and print the result.

There is a lot wrong with this program. Identify all the errors, explain exactly what is wrong with each, and why it is wrong, and tell me how to put it right. Do not just write a correct program. The point of this problem is to show that you can identify the mistakes and that you can work out how to fix each of them individually.

It is not cheating to use a computer to help you to find the mistakes. Just don’t expect it to explain them to you.

#include

#include

void main(void)

{ int num=0;

cout > num;

string Arr[num];

// read the strings

while (!cin.error())

{ cin >> s;

num=num+1;

Arr[num]=s; }

// sort them

for (int i=0; i> s; should be followed by if (cin.error()) break;. The loop condition can still be used to make sure we don’t read too much data.

In fact, the program is quite confused here. Why bother asking the user how much they are going to type if you’re going to check for end-of-file anyway? But then, how does end-of-file help when you are reading from cin? How can you “end” your keyboard? (the answer is “easiliy”, under unix just type ctrl-D).

And the function is called fail, not error, anyway.

3. And of course, the loop is ruining the variable “num”. Num was used to store the (expected) size of the array. Adding one to it guarantees that we will be accessing the array beyond its proper end. Clearly we want another independent variable to control the loop and be incremented. Perhaps the while (...) should become for (int i=0; i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download