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
Not so good things
// A solution to problem A by Stuart Inglis, in C
#include < string.h >
#include < stdlib.h >
#include < stdio.h >
#include < assert.h >
#define MAXLEN (60+1+1)
int main(void)
{
FILE *infile;
infile=fopen("PROBLEMA.DAT", "rt");
assert(infile);
while(1){
char linebuffer[MAXLEN],*p;
int count,len;
fgets(linebuffer,MAXLEN,infile);
len=strlen(linebuffer);
if(linebuffer[len-1]=='\n') linebuffer[len-1]='\0';
if(strcmp(linebuffer,"#")==0) break;
count=0;
p=strtok(linebuffer," ");
while(p){
count++;
p=strtok(NULL," ");
}
fprintf(stdout,"The line contains %d words\n",count);
};
fclose(infile);
return 0;
}
|