Thread: Code Critique
View Single Post
Old Jun 2nd, 2006, 6:55 PM   #5
darthsabbath
Newbie
 
Join Date: Dec 2005
Posts: 15
Rep Power: 0 darthsabbath is on a distinguished road
Quote:
Originally Posted by grumpy
My third comment is about a real problem in your code; that problem is a showstopper. If your user inputs a space as the first character (or a '\n' or a '\t' ....) the program yields undefined behaviour. This is because of a basic flaw in your program logic. Read the comments in the code snippet I gave to see why.

The point of my 4th comment is to use isspace() from <ctype.h>. That is a minor improvement, which has nothing to do with addressing the preceding problem of undefined behaviour.
Sorry, I was actually trying to solve both 3. and 4. Shows what I get for trying to do this on break. :-) I should have been more clear.

At any rate, I added an additional test to the second if statement (see comments), only entering the statement if nc is between 0 and MAXSIZE.

When I get home I'm going to work on this some more. I do appreciate the help, though! :-)

 
while ((c = getchar()) != EOF) { 
   ++nc; /* Increment to 1*/
   if (isspace(c) ){   	 	
      --nc; /* Toss out the space, nc is now 0 */
      if ((nc > 0) && (nc < MAXSIZE)) { /* This test fails if nc is 0, correct? */
         ++arr[nc-1];
         nc = 0;
      } else if (nc > MAXSIZE) {
          arr[MAXSIZE]++;
          nc = 0;
      }
   }
}
darthsabbath is offline   Reply With Quote