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
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.
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?
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;
}
#include <cstdlib>
#include <iostream>
#include <string>
usingnamespace std;
void count1(const string &s)
{
int counts[10] = {0};
for (unsignedint 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 = newint [size];
for (int i=0; i<size; i++)
counts[i] = 0;
for (unsignedint 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
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;
}
}