Incrementing elements in an array?

I'm trying to write code which will count the number of instances of each digit in a given string. However nothing I try will allow me to increment the value at ch in the counts[] array. The error is most certainly on line 16, but what am I doing wrong?

Intended output is:
counts[1] is 1, counts[2] is 2, counts[3] is 3

Actual output is:
counts[0] is 0, counts[0] is 0, counts[0] is 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
  #include <cstdlib>
#include <iostream>
#include <string>
using namespace std;


int * count1(const string &s){
        int counts[10] = {0};
        
        for(int i = 0; i<s.length(); i++)
        {   
                int ch = 0;
                do{     
                          if(ch == s.at(i))
                          {   
                              counts[ch] = counts[ch]+1;
                          }
                          ch++;
                }while(ch < 9);      
        }

        for(int i = 0; i < 10; i++) //go through all elements
        {
                cout << "counts["<< i << "] is "<< counts[i] << endl;
        }
}
        
int main(int argc, char *argv[])
{
    const string test1("122 333 444455555");
    count1(test1);
    

    
    system("PAUSE");
    return EXIT_SUCCESS;
}
Last edited on
I'm not sure why you are getting that output, but you should make your count1() function void return type.

EDIT: oh yes,
ch == s.at(i) //ch is an int (0) whereas s.at(i) is a char ('0').
Last edited on
I think your while loop also.You want to compare the one element with the rest with in a string.
Store the element in a temporary srting, iterate through the entire string comparing it.

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

void *count1(const string &s){
       int k = 0;
        
        for(int z = 0; z<s.length(); z++)
        {   
		
		string str;
                int ch = 0;
		int i = 0;
		str[k] = s[z];
		
		
		while(i < s.length())
                {     
		
                          if(str[k] == s[i])
                          {   
				   ch++;
                          }
			  i++;
                       
                }    
		 cout << "counts["<< k << "] is "<< ch<< endl;	
		k++;
	
        }

      
               
      


Please just change it to suit what you want.You could also use a isspace function to avoid spaces in the string.
Please try it and let me know.I am on windows and didnt try it.
All the best
Thank you. I changed the counts[] and ch declarations to char and put single quotes around each assignment.

X
However, the code is now returning:
counts[0] is 0, counts[1] is , counts[2] is
X
Edit: sorry, code is actually returning an infinite loop at line 22.
How can I create the for loop with characters correctly?
Last edited on
can you post you edited code
@ngopza

Your code works outputs the character at each location in the string given, rather than the number of instances of each digit.
Here is the updated code.

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
int * count1(const string &s){
        char counts[10] = {'0'};
        
        for(int i = 0; i<s.length(); i++)
        {  
                char ch = '0';
                do{     
                          if(ch == s.at(i))
                          {   
                              counts[ch]++;
                          }
                          ch++;         
                }while(ch < 9);        
        }
           
        for(char ch = '0'; ch < '10'; ch++) //go through all elements
        {
                cout << "counts["<< ch << "] is "<< counts[ch] << endl;
        }
}
    
int main(int argc, char *argv[])
{
    const string test1("122 333 444455555");
    count1(test1);
    
    system("PAUSE");
    return EXIT_SUCCESS;
}
You are getting confused between array index and value at that index. An index shall always be an (unsigned) int. A value may have any type.

1
2
3
4
5
6
7
8
9
10
11
12
13
do{     
                          if(ch == s.at(i))
                          {   
                              counts[ch - '0']++; // again convert char to int.
                          }
                          ch++;         
                }while(ch <= '9'); // I assume you also want to count the 9s

for(int ch = 0; ch < 10; ch++) //remove the char, now ch is an index
        {
                cout << "counts["<< ch << "] is "<< counts[ch] << endl;
        }
'10' is not a char. Illegal line 16.

The numeric value of '0' is not 0. You attempt to write to elements counts[X], where X is not in range [0-9].

Convert ch to integer before line 10. Plain atoi() might suffice. Well, not quite; you have nondigits in input.
Below, count1() is based upon the original code. count2() is a variation.
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
40
41
42
43
44
45
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

void count1(const string &s)
{
    int counts[10] = {0};

    for (unsigned int i = 0; i<s.length(); i++)
        for (int ch = 0; ch<=9; ch++)
            if (ch+'0' == s.at(i))
                counts[ch]++;

    for (int i = 0; i < 10; i++)
        cout << "counts["<< i << "] is "<< counts[i] << endl;
}

void count2(const string &s, const string & letters)
{
    int size = letters.size();

    int *  counts = new int [size];
    for (int i=0; i<size; i++)
        counts[i] = 0;

    for (unsigned int i = 0; i<s.length(); i++)
        for (int j=0; j<size; j++)
            if (letters[j] == s[i])
                counts[j]++;

    for (int i = 0; i < size; i++)
        if (counts[i])
            cout << "character '"<< letters[i]  << "' occurs "<< counts[i] << endl;

    delete [] counts;
}

int main()
{
    const string test1("122 333 444455555");
    count1(test1);
    count2(test1, "124");
}

Output:
counts[0] is 0
counts[1] is 1
counts[2] is 2
counts[3] is 3
counts[4] is 4
counts[5] is 5
counts[6] is 0
counts[7] is 0
counts[8] is 0
counts[9] is 0
character '1' occurs 1
character '2' occurs 2
character '4' occurs 4
@Graeme Hart your "updated code" with errors fixed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void count1(const string &s){
    int counts[10] = {0};
    
    for (int i = 0; i<s.length(); i++)
    {  
        char ch = '0';
        do {     
            if (ch == s.at(i))
            {   
              counts[ch-'0']++;
            }
            ch++;         
        } while (ch <= '9');        
    }
       
    for (int i = 0; i <= 9; i++) // go through all elements
    {
            cout << "counts["<< i << "] is "<< counts[i] << endl;
    }
}
Last edited on
Got everything sorted and understand it too! Thanks a bundle guys.
Topic archived. No new replies allowed.