Write a C program which reads a text, and print it out one word per line, all punctuation and non-alpha characters being omitted. When typing input, end the data by typing the end-of-file character usually control+D.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#include <ctype.h>
#define SIZE 500

int main(int argc, char ** argv) {
    int i;
    char c, text[SIZE];

    for (i = 0; i < SIZE - 1 && (c = getchar()) != EOF; i++)
        text[i] = c;
    text[i] = '\0';

    for (i = 0; text[i] != '\0'; i++) {
        if (isspace(text[i]))
            printf("\n");
        else {
            if (ispunct(text[i]) || !isalpha(text[i]))
                continue;
            else
                putchar(text[i]);
        }
    }
    return 0;
}

When you compile and execute the above program it produces the following result on Linux:

I love C programming. Keep visiting divostar.com and learn C for free.

I
love
C
programming
Keep
visiting
divostarcom
and
learn
C
for
free

Brief Explanation

  • The program starts by reading text from input using the function getchar until either there is no more space in the character array or the end-of-file is reached (Ctrl + D). Once the text is read into the array, the variable i is one place after the last character. The string terminator (\0) is assigned to this position.
  • Using another for loop and functions isspace, ispunct, isalpha and putchar, words are extracted from the text and printed one word per line.
  • The function isspace is used to determine whether a character is a space.
  • The function ispunct is used to determine whether a character is a punctuation.
  • The function isalpha is used to determine whether a character is a letter.
  • The function putchar is used to display a character.
  • The function getchar is used to read a character.
  • The functions isspace, ispunct and isalpha are defined in the ctype library.

Add comment


Security code
Refresh