
- Forum
- Programming Talk
- C and C++
- Need help to get this program work correctly.
Need help to get this program work correctly.
This is a discussion on Need help to get this program work correctly. within the C and C++ forums, part of the Programming Talk category; I am new to programming and writing a C Program to count words, characters and newlines. I came up with ...
-
Need help to get this program work correctly.
I am new to programming and writing a C Program to count words, characters and newlines. I came up with this code and like to know people opinion on it. I have written the same program using the do-while but unfortunately I am not getting the desired result. Please I will be grateful for any help to rectify the problem.
Code:While Loop Version
Code:// counts characters, words, lines #include <stdio.h> #include <ctype.h> // for isspace() int main(void) { char c; // read in character long n_chars = 0L; // number of characters int n_lines = 0; // number of lines int n_words = 0; // number of words int inword = 0; // == true if c is in a word printf("Enter text to be analyzed (return then Ctrl+Z to terminate):\n\n"); while ((c = getchar()) != EOF) { n_chars++; // count characters if (c == '\n') n_lines++; // count lines if (!isspace(c) && !inword) { inword = 1; // starting a new word n_words++; // count word } if (isspace(c) && inword) inword = 0; // reached end of word } printf("characters = %ld, words = %d, lines = %d, \n", n_chars, n_words, n_lines); return 0; }Code:Do-while Loop Version returns more than expected number of words and characters
Code:// counts characters, words, lines #include <stdio.h> #include <ctype.h> // for isspace() int main(void) { char c; // read in character long n_chars = 0L; // number of characters int n_lines = 0; // number of lines int n_words = 0; // number of words int inword = 0; // == true if c is in a word printf("Enter text to be analyzed (return then Ctrl+Z to terminate):\n\n"); do { c = getchar(); n_chars++; // count characters if (c == '\n') n_lines++; // count lines if (!isspace(c) && !inword) { inword = 1; // starting a new word n_words++; // count word } if (isspace(c) && inword) inword = 0; // reached end of word } while (c != EOF); printf("characters = %ld, words = %d, lines = %d, \n", n_chars, n_words, n_lines); return 0; }

Reply With Quote





