memory - Error in C with word counting program using switch statement -


i having trouble counting number of words user enters using switch statement. want ensure multiple presses of keyboard (ascii,32) not count multiple words. can see, have memory variable stores previous keyboard press, , want count word when current keyboard press space, , previous press (i.e. memory variable not space). logic makes perfect sense me; however, code not seem work. please explain flaw in logic is? thanks.

// 1.4 exercise 1: output amount of characters, number of words , number of newlines typed user  // note escape command on mac enter command z #include <stdio.h>  int main() {     long characters = -1; // exit program on mac must press command+z      long newlines = 0;     long words = 1; // assume document starts word       printf("type stuff! exit type ctrl+d (some computers use ctrl+z space)\n");      int = 0;     int memory = 32; //stores previous keyboard press        while (i != eof) // characters continue counting long escape sequence not entered      {         = getchar(); //assign integer output of buffered getchar() function           if (i != 10)         {             characters++;         }          switch (i)         {         case 10: // enter key press         {             newlines++;             break; // exit switch (each character unique)          }         case 32: // space          {             if (memory != 32) // if previous character press not space, words++             {                 words++;             }             memory = i; // stores previous keyboard press             break; // exit switch (each character unique)          }         default: break; //exit switch default action if previous switches not true          }     }      printf("%d characters typed\n", characters);     printf("%d words typed\n", words);     printf("%d lines typed\n", newlines);      return 0; } 

you updating value of memory when inside of case statement when = 32. this, value of memory 32. instead, should update value of memory after switch statement closed. i.e.

switch(i) {     /* code here */ } memory = 

as side note, make code more readable , aid portability if don't hard-code ascii values of characters switch statement. can instead write them using character.

switch(i)  {     case '\n':         /* code */         break;     case ' ':         /* code */         break; } 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -