Error - 'counter' was no declared in scope


Can someone please tell me what I've done wrong here? I'm getting the error 'counter' was no declared in scope

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
39
 
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string word = "";

    do
    {
        cout << "Enter a word that has at least 5 characters: " << endl;
        cin >> word;
    }while(word.size() < 5);


    char searchCh = '0';
    cout << "Enter a character and the program will tell you how many times it appears in the word " << word << "." << endl;
    cin >> searchCh;


    for(int i = 0; i < (int)word.size(); i++)
    {
        char ch = word.at(i);

        if(searchCh == ch)
        {
            counter++;
        }

    }

    cout << "The number of " << searchCh << "'s in the word " << "is " << counter << ".\n";

    return 0;
}

You forgot to declare the variable 'counter' (int counter = 0;) in your code. Thanks for using coding tags. ^_^

By the way instead of
1
2
3
4
5
6
        char ch = word.at(i);

        if(searchCh == ch)
        {
            counter++;
        }

you can also do
1
2
3
4
        if(searchCh == word[i])
        {
            counter++;
        }


Also string word = ""; is the same as string word;
Last edited on
Thanks very much. That all works now! :)
Topic archived. No new replies allowed.