gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Check char array only contains uppercase letters

#168217 - hamm - Wed Apr 15, 2009 7:12 pm

Hi,

i need to know how to check an char array of uppercase letters. There should be a error message if it contains lowercase letters, numbers, whitespaces etc etc...

Need help please ??
Thanks!

#168219 - Cearn - Wed Apr 15, 2009 7:41 pm

Read up on ctype.h. This header declares some useful functions for character types, including if they're uppercase. Example:

Code:
#include <ctype.h>

//! Check if a string is composed entirely of uppercase characters.
bool strIsUpper(const char *str)
{
    int i;
    for(i=0; str[i] != '\0'; i++)
        if( !isupper(str[i]) )
            return false;
    return true;
}

#168220 - DiscoStew - Wed Apr 15, 2009 7:45 pm

http://www.asciitable.com/

Uppercase letters range from value 65 to 90. If you can scan each char in the array, you can compare the value to the Uppercase range. If it is within (and including) the range, then keep scanning. If not, then error out. This could be set into a simple function, where if it errors out, you simply return false, but if it scanned the entire array with no error, then return true.

EDIT:

Basically what Cearn posted, except without using <ctype>, and doing the checking manually. :P
_________________
DS - It's all about DiscoStew

#168221 - hamm - Wed Apr 15, 2009 7:56 pm

Thank you very much!!! And sorry, I was really blind ??

#168222 - Dwedit - Wed Apr 15, 2009 8:22 pm

Obviously, this is ASCII only, and excludes uppercase international characters.
_________________
"We are merely sprites that dance at the beck and call of our button pressing overlord."

#168225 - sgeos - Wed Apr 15, 2009 11:57 pm

DiscoStew wrote:
Uppercase letters range from value 65 to 90.

You could check that the character is between 'A' and 'Z'. This way you don't have to remember the ascii values and in theory your code will not break if the compiler uses a non-ascii ascii-compatible encoding.
Code:
// no need for ctype

bool strIsUpper(const char *pString)
{
    int i;
    for (i = 0; pString[i] != '\0'; i++)
        if ( pString[i] < 'A' || 'Z' < pString[i] )
            return false;
    return true;
}

#168239 - Miked0801 - Thu Apr 16, 2009 5:24 pm

Homework assignment perhaps?

#168269 - sgeos - Fri Apr 17, 2009 5:37 pm

Perhaps, but upon rereading nobody actually posted anything completely to spec.

#168287 - Kyoufu Kawa - Sun Apr 19, 2009 2:34 pm

sgeos wrote:
Perhaps, but upon rereading nobody actually posted anything completely to spec.
Working from Cearn's post.
Code:
void UpToSpec(const char *str)
{
    if(!strIsUpper(str))
    {
        printf("Your error message here.\n");
    }
}