Solution for Exercise 13-14

ex1314

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

int main()
{
    char phrase[] = "When in the Course of human events, it becomes
necessary for one people to dissolve the political bands which have
connected them with another, and to assume among the powers of the
earth, the separate and equal station to which the Laws of Nature
and of Nature's God entitle them, a decent respect to the opinions
of mankind requires that they should declare the causes which impel
them to the separation.";

    int index;
    int alpha,blank,punct;

    alpha = blank = punct = 0;

/* gather data */
    index = 0;
    while(phrase[index])
    {
        if(isalpha(phrase[index]))
            alpha++;
        if(isblank(phrase[index]))
            blank++;
        if(ispunct(phrase[index]))
            punct++;
        index++;
    }

/* print results */
    printf("\"%s\"\n",phrase);
    puts("Statistics:");
    printf("%4d alphabetic characters\n",alpha);
    printf("%4d blanks\n",blank);
    printf("%4d punctuation symbols\n",punct);

    return(0);
}

Notes

* As I wrote in the notes for Exercise 13-1, the text for the phrase[] variable above is broken between several lines. If you copy and paste this code into an editor, delete the line breaks so that you have one, long unbroken string of text.

* The only major difference between this code and the solution for Exercise 13-1 is the modification of the %d placeholders in the final three printf() statements from %d to %4d.

* I chose %4d in the final printf() statements, even though in this example, the widest result is three-digits long. Why not use %3d? Because the code should be flexible and allow for any text example, not just mine.