user1145538
user1145538

Reputation: 647

Using a different library in C

I just coded from scratch a program that would count the upper and lowercase letters and blank spaces of whatever the user input. Since then I found out that code for those specific functions have already been prewritten in another library! My question is, how can all the code that I have written below be simplified with the use of

isupper(int c), islower(int c), and isspace(int c) which are defined in ctype.h.

#include <stdio.h>

int main(void){
int iochar, numdigits=0, numlower=0, numupper=0, numwhites=0;

printf("Please enter a phrase:\n\n");

while((iochar=getchar())!=EOF) 
{
    if ((iochar==' ')||(iochar=='\t')||(iochar=='\n'))
    {
        numwhites++;
        putchar(iochar);
    }
    else 
        if((iochar>='0')&&(iochar<='9')) 
        {
            numdigits++;
            putchar(iochar);
        }
        else 
            if(('a'<=iochar)&&(iochar<='z')) 
            {
                numlower++;
                putchar(iochar-32);
            } 
            else 
                if(('A'<=iochar)&&(iochar<='Z'))
                {
                    numupper++;
                    putchar(iochar);
                }
                else 
                    putchar(iochar);    
}

printf("%d white characters, %d digits, ",numwhites,numdigits);
printf("%d lowercase have been converted to ",numlower);
printf("uppercase and %d uppercase.\n",numupper);

printf("\n\n");


return 0;}

Upvotes: 0

Views: 122

Answers (2)

orlp
orlp

Reputation: 117781

Here is it written better and cleaned up:

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

int main(int argc, char **argv) {
    int iochar, numdigits=0, numlower=0, numupper=0, numwhites=0;

    printf("Please enter a phrase:\n\n");

    while ((iochar=getchar()) != EOF) {
        // increase counts where necessary
        if (isspace(iochar)) {
            numwhites++;
        } else if (isdigit(iochar)) {
            numdigits++;
        } else if (islower(iochar)) {
            numlower++;
            iochar = toupper(iochar);
        } else if (isupper(iochar)) {
            numupper++;
        }

        // this happens always, don't put it in the if's
        putchar(iochar);
    }

    printf("%d white characters, %d digits, ", numwhites, numdigits);
    printf("%d lowercase have been converted to ", numlower);
    printf("uppercase and %d uppercase.\n", numupper);

    printf("\n\n");

    return 0;
}

Upvotes: 5

Paul R
Paul R

Reputation: 213130

Just #include <ctype.h> and then change e.g.

if((iochar==' ')||(iochar=='\t')||(iochar=='\n'))

to

if (isspace(iochar))

etc.

For full details see man ctype.

Upvotes: 1

Related Questions