-1

I have a function which takes a string as an argument. What I want to do is check if the string starts with an upper case letter. If this is true, then I want to return true. If it does not start with an upper case letter then I wish to return false. Simple enough?

The code I was using is this:

bool filter(string word)
    {
        char cWord[50];
        char c;
        for(int i = 0; i <= word.size(); i++)
        {
            cWord[i] = word[i];
        }
        c = cWord[0];
        if(isupper(c)){return true;}
        else{return false;}
    }

However I don't think it functions how I would like it to. Can anyone confirm that my function should work correctly, or whether there is a better way to check if the first character is a capital letter?

3
  • I don't see anything wrong with it. Just be aware that isupper takes into account the system locale to decide wether the char it receives is an upper case letter or not.
    – Spidey
    Jan 13, 2013 at 16:29
  • 1
    Why did you copy the string? I assume string is std::string and isupper is std::isupper? Jan 13, 2013 at 16:43
  • 1
    Also, you are vulnerable to buffer overflows... What happens if word is 50 characters or more? Jan 13, 2013 at 16:44

3 Answers 3

14

This should be as simple as this:

bool firstUpper(const string& word) { return word.size() && std::isupper(word[0]); }
3
  • 1
    This, but also think about what you want for empty string.
    – zch
    Jan 13, 2013 at 16:31
  • 3
    I think !word.empty() or word.size() > 0 would be less confusing than word.size(). You should probably also use std::isupper.
    – ronag
    Jan 13, 2013 at 16:41
  • 1
    For me word.size() is not confusing and it shouldn't really be for any competent C++ programmer. OK for std::isupper.
    – piokuc
    Jan 13, 2013 at 16:46
2

You can simply use std::isupper from the header <cctype>, after checking that the string isn't empty.

bool filter(const std::string& word)
{
  return (!word.empty()) && std::isupper(word[0]);
}
2
  • 1
    @juanchopanza: Well that's the question isn't it! Nobody's answered it yet, mainly because we don't know what the question is. Jan 13, 2013 at 16:38
  • 2
    @LightnessRacesinOrbit I should stop assuming that the title of a question carries any relevance :-) Jan 13, 2013 at 16:40
0

Your function works as long as your argument word is shorter than 50 characters. If word is longer, you will overwrite cWord and corrupt your stack. As others already have shown, there is no need to copy word for testing the first character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.