Function to count capital letters in string

I am trying to make a function that will tell me if any letters in a spring are capitalized. For simplicity, I just made it test for A. I have been trying different method, but always outputs 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 #include <cstdlib>

#include <iostream>

#include <string>

#include <cctype>

#include <ctype.h>

#include <algorithm>
using namespace std;

int countCapital(string, int); 

int main()
{
   int capitalCount;
   string custNames = "";
   custNames = "kAren b. wang!marrisa g. madison";
   capitalCount = countCapital(custNames, capitalCount);
   cout <<capitalCount<<endl;
   return 0;
}

int countCapital(string custNames, int capitalCount)
 {
    for (int i=0; i <=custNames.size(); ++i)
    {
        int capitalCount = 0;
     if (custNames[i] == 'A')
        {
            capitalCount = capitalCount + 1;
        }
    }
   return capitalCount;   
 }
 
1
2
3
4
5
6
7
8
int countCapital(string custNames)
{
    int capitalCount(0);
    for (char c: custNames)
        if (isupper(c))
            ++capitalCount
    return capitalCount;   
}
Line 30 is declaring a local capitalCount variable within your for-loop. Line 33 is incrementing that local, rather than the function-parameter returned at line 36 - which remains at zero the whole time. Also, because it's declared inside the for-loop, it's re-declared and re-created every time round the loop.

You don't need to have the capitalCount function-parameter at all as you're not doing anything with the information it gives inside the function.

So, 1) remove the capitalCount parameter, and 2) move your local declaration before the start of the for-loop so it's not reset every loop iteration.

Cheers,
Jim
@MiiNiPaa

1
2
3
4
5
6
7
8
int countCapital(string custNames)
{
    int capitalCount(0);
    for (char c: custNames)
        if (isupper(c))
            ++capitalCount
    return capitalCount;   
} 



1
2
3
4
5
6
7
8
9
10
11
std::string::size_type countCapital( const std::string &custNames )
{
    std::string::size_type capitalCount = 0;

    for ( char c : custNames )
    {
        if ( std::isupper( c ) ) ++capitalCount;
    }

    return capitalCount;   
} 
Topic archived. No new replies allowed.