livin_DA_Life
livin_DA_Life

Reputation: 21

How do you ignore numeric input using getchar and putchar

I am new to C programming. One of my assignment questions is giving me a hard time. Here it is:

Write an ANSI-C program that uses getchar() to read characters from the standard input, and uses putchar() to output only the letters, spaces (' ') and newlines in the input to the standard output. If the letters are lower case letters, your program should convert them into upper cases. For example, given the following input:

There are 6 apples and 8 oranges, also 9 bananas ...... @ Apple Store!! See you there!?
the output of your program should be:
THERE ARE APPLES AND ORANGES ALSO BANANAS APPLE STORE SEE YOU THERE

I can get the capitalization part right but am having a hard time with ignoring numbers and any other character. Any help would be much appreciated.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int c;

    while ((c=getchar())!=EOF) {
        if ((c>='a' && c<='z'))
            c -= 32;
        else
            while((c==getchar())<'a' || (c==getchar())>'z' ||(c==getchar())!='\n' ||(c==getchar())!=' ');  //This is where I am having trouble.
        putchar(c);
    }
}

Upvotes: 2

Views: 1546

Answers (3)

Orest Hera
Orest Hera

Reputation: 6776

You can use something like that:

char char_filter(char c)
{
    /* lower case letters */
    if (c >= 'a' && c <= 'z')
        return c - ('a' - 'A');

    /* upper case letters*/
    if (c >= 'A' && c <= 'Z')
        return c;

    /* space and new line */
    if (c == ' ' || c == '\n')
        return c;

    /* other characters */
    return 0;
}

Here if the function returns zero the char should be skippted otherwise it should be printed by putchar:

char c;
while ((c = getchar()) != EOF) {
    if ((c = char_filter(c)))
        putchar(c);
}

Note that there are also standard functions int islower(int c), int isupper(int c) and int isspace(int c). The function isspace() considers as a space also '\t', '\n' and some other characters.

Upvotes: 0

BLUEPIXY
BLUEPIXY

Reputation: 40145

Use isalpha, isspace and toupper in <ctype.h> like this

while ((c=getchar())!=EOF) {
    if(isalpha(c) || isspace(c))// isspace allow '\t' => c == ' ' || c == '\n'
        putchar(toupper(c));
}

Upvotes: 2

Paul92
Paul92

Reputation: 9062

Just use the isdigit function to check if a character is a digit or not. If it is not a digit, process it as you seem to do now. Otherwise, just ignore it and try to read another character.

Upvotes: 0

Related Questions