0

I'm writing a program that counts the number of words and the number of lines. I tried to count spaces and tabulators but it does not work. For example if the input is:

Hello..\n \tI love coding!\n Do you?

The output will be 2 lines 4 words

#include <stdio.h>
#include <stdlib.h>
#define INT_MAX (100000000)

int is_newline(int c) {

    return (c =='\n');

}
int is_word(int c){
    return (c == ' ' || c == '\t');
}
int main(void) {
    int ch;
    int num_words = 0;
    int new_line = 0;

    ch = getchar();
    while (ch != EOF) {
        if (is_word(ch)) {
            num_words++;
        }else if (is_newline(ch)) {
            new_line++;
            num_word++;
        }
        ch = getchar();
    }
    printf("The number of words is: %d", num_words);
    printf("The number of line is: %d", new_line);
    return 0;
}
User21749
  • 35
  • 2
  • 7
  • 1
    It's duplicating post, see : [Counting words in a string - c programming](https://stackoverflow.com/questions/12698836/counting-words-in-a-string-c-programming) – Louis Zwawiak Apr 24 '19 at 08:35
  • 1
    Please post real code. What is `num_word`? And why are you redefining `INT_MAX`? – Jabberwocky Apr 24 '19 at 08:36
  • 3
    Betty, your logic has errors. If you step through the program with a debugger, they will be easy to find. – Paul Ogilvie Apr 24 '19 at 08:36
  • 1
    Unrelated. Try not to use standard-defined names. `INT_MAX` is defined by the standard in ``. If you need it, use *that*; don't make it up. – WhozCraig Apr 24 '19 at 08:43
  • The number of sentences is 2 because you don't count the last one (because there is not a `\n` after it). – Davide Visentin Apr 24 '19 at 09:21
  • Some like this: `if is_whitespace then { word_count++, while(is_whitespace) {if char is NL then NL_count++, get_char}}` – Igor Galczak Apr 24 '19 at 09:22

0 Answers0