1

The following code reads from the stdin stream character by character until it encounters an EOF symbol (CTRL-D). However, when I execute the CTRL-D command it does not process it as an EOF character.

#include <stdio.h>
#include <ctype.h>

int main() {

    char current_character, next_character;

    int amount_of_characters = 0, amount_of_words = 0, amount_of_newlines = 0;

    while( (current_character = getchar()) != EOF) {
        amount_of_characters++;

        if(isspace(current_character) || current_character == '\n') {

            next_character = getc(stdin);

            if(isalpha(next_character)) {
                amount_of_words++;
                ungetc(next_character, stdin);
            }

            if(current_character == '\n') {
                amount_of_newlines++;
            }
        }
    }

    printf("----- Summary -----\n");
    printf("Characters: %d\nWords: %d\nNewlines: %d\n", amount_of_characters, amount_of_words, amount_of_newlines);

    return 0;
}
Mutating Algorithm
  • 2,604
  • 2
  • 29
  • 66
  • Note that typing control-D isn't identical to EOF — though it often triggers the EOF condition. EOF is not really a character — it is distinct from every valid character (which is why `getchar()` and its relatives return an `int` rather than a `char`). – Jonathan Leffler Apr 25 '19 at 23:36
  • Did you mean `while( (current_character = getchar()) != EOF) {`? Your existing condition with `==` exits immediately, of course. – Jonathan Leffler Apr 25 '19 at 23:37
  • 3
    getchar() returns an int. current_character is a char. – wildplasser Apr 25 '19 at 23:40

0 Answers0