A solution to Problem A (5 point)

There are many ways of solve problem A. This program demonstrates several things. This was a question from the N.Z. 1995 programming competition. There were teams (from Auckland :-) that could not do this in five hours.

This is how I would do it. If you know a better way, let me know, that's how we all learn.

Good things
• The use of assert(). This is the greatest command you can ever use. Use it lots. It will become your friend. :-)
[True! Assert is an ideal way of catching design or programming errors. Normally one should NOT use assert to catch RUNTIME errors, so things like files not opening properly should be handled by outputting a message, or by throwing an exception. But in this programming competition, where user-interface is irrelevant, using assert to do it is okay. Mark Utting]
• I/O from a string instead of a file. This allows you to grab the entire line and then process the string as if you were reading from a normal file.
• Not so good things
• Compile time constants. We are told the limits for this problem, but what would you do if a line could be any length?
• Why 60+1? C++ strings are delimited by a 0. So we need 60 characters for the line and one more for the end-of-string specifier.
• infile.getline() is nasty if the line is too long. assert(infile.getline(..)) is one way, looking at infile.gcount() if the command fails is another.

• ```// A solution to problem A by Stuart Inglis, in C++

#include < iostream.h >
#include < strstream.h >
#include < fstream.h >
#include < assert.h >

#define MAXLEN 60+1

int main(void)
{
ifstream infile("PROBLEMA.DAT", ios::in);
assert(infile);

while(1){
char linebuffer[MAXLEN],word[MAXLEN];

infile.getline(linebuffer,MAXLEN);

if(strcmp(linebuffer,"#")==0) break;

istrstream strbuffer(linebuffer,strlen(linebuffer));

int count=0;
while(strbuffer >> word)
count++;

cout << "The line contains " << count << " words" << endl;
};
return 0;
}

```