stryder9k
stryder9k

Reputation: 11

How would I put an "if" statement into this code to check for non-alphabet characters?

The code is for turning alphabet numbers from lower case to upper case and vice versa; however if non-alphabet characters are inserted it should return an error.

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

int main (void)
{
    int c = 0;
    char ch, s[1000];

    printf("Enter a string of upper and lower case letters\n");
    scanf("%s", s);
}

Upvotes: 0

Views: 74

Answers (1)

David Ranieri
David Ranieri

Reputation: 41045

Always protect your code from bufffer overflows:

scanf("%999s", s);

instead of

scanf("%s", s);

regarding your question, you can use isalpha and tolower, toupper:

#include <ctype.h>
...
scanf("%999s", s);

char *p = s;

while (*p)
{
    unsigned char c = (unsigned char)*p;

    if (!isalpha(c))
    {
        // there are non alpha chars
        // return 0;
    }
    else
    {
        *p = islower(c) ? toupper(c) : tolower(c);
    }
    p++;
}

Upvotes: 2

Related Questions