Guest User

Untitled

a guest
Jul 16th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <ctype.h> //This is to bring in the declaration of isspace()
  3. #include <stdbool.h> //This is to bring in the define of true
  4.  
  5.  
  6. #define kMaxLineLength 200
  7. #define kZeroByte 0
  8.  
  9. void ReadLine( char *line );
  10. int CountWords( char *line );
  11.  
  12. int main (int argc, const char * argv[]) {
  13. char line[ kMaxLineLength ];
  14. int numWords;
  15.  
  16. printf( "Type a line of text, please:\n" );
  17.  
  18. ReadLine( line );
  19. numWords = CountWords( line );
  20.  
  21. printf( "\n---- This line has %d word", numWords );
  22.  
  23. if ( numWords != 1 )
  24. printf( "s" );
  25.  
  26. printf( " ----\n%s\n", line );
  27.  
  28. return 0;
  29. }
  30.  
  31.  
  32. void ReadLine( char *line ) {
  33. int numCharsRead = 0;
  34.  
  35. while ( (*line = getchar()) != '\n' ) {
  36. line++;
  37. if ( ++numCharsRead >= kMaxLineLength-1 )
  38. break;
  39. }
  40.  
  41. *line = kZeroByte;
  42. }
  43.  
  44.  
  45. int CountWords( char *line ) {
  46. int numWords, inWord;
  47.  
  48. numWords = 0;
  49. inWord = false;
  50.  
  51. while ( *line != kZeroByte ) {
  52. if ( ! isspace( *line ) ) {
  53. if ( ! inWord ) {
  54. numWords++;
  55. inWord = true;
  56. }
  57. }
  58. else
  59. inWord = false;
  60.  
  61. line++;
  62. }
  63.  
  64. return numWords;
  65. }
Add Comment
Please, Sign In to add comment