Masnad Nehith - 10 months ago 35

C++ Question

I am writing a program which has a string, and then I read through the string and put all the digits in a array using vector and then using count I have to count the same numbers in that array and after that print the number as stars.

Error I am getting is invalid operands to binary expression.

Here is the code.

`#include <iostream>`

#include <vector>

#include <algorithm>

#include<array>

using namespace std;

int main() {

vector<string> array;

string grades = "01211342111153332211111232454444";

int newarray[31];

for(int i = 0 ; i < grades.length(); i++){

array.push_back(grades.substr(i,1));

}

int zero = count(std::begin(array),std::end(array),0);

int one = count(std::begin(array),std::end(array),1);

int two = count(std::begin(array),std::end(array),2);

int three = count(std::begin(array),std::end(array),3);

int four = count(std::begin(array),std::end(array),4);

int five = count(std::begin(array),std::end(array),5);

// also used this way int zero = count(array.begin(),array.end(),0); but still getting error.

for(int i = 0 ; i < one ; i ++){

cout << '1 - ' << '*' << ' ';

}

for(int j = 0 ; j < two ; j++){

cout << '2 - ' << '*' << ' ';

}

}

Learning C++ so hopefully people go a bit easy on me.

Answer Source

Many issues here.

First, you are comparing number to strings in `int zero = count(std::begin(array),std::end(array),0);`

. You want to compare string to string.

Second, you are trying to `cout`

`'1 - '`

. `'`

is for characters, so you should use `"`

instead.

Finally, in the `cout`

, you need to loop only on the stars and the space, not the `"1 - "`

. And flush the whole thing to print on your console, with either `cout<<"\n";`

or `cout<<std::endl;`

.

You can try the following:

```
int main()
{
vector<string> array;
string grades = "01211342111153332211111232454444";
int newarray[31];
for(int i = 0 ; i < grades.length(); i++){
array.push_back(grades.substr(i,1));
}
int zero = count(std::begin(array),std::end(array),"0");
int one = count(std::begin(array),std::end(array),"1");
int two = count(std::begin(array),std::end(array),"2");
int three = count(std::begin(array),std::end(array),"3");
int four = count(std::begin(array),std::end(array),"4");
int five = count(std::begin(array),std::end(array),"5");
cout << "1 - ";
for(int i = 0 ; i < one ; i ++){
cout << '*' << ' ';
}
cout << "\n";
cout << "2 - ";
for(int i = 0 ; i < two ; i ++){
cout << '*' << ' ';
}
cout << "\n";
/*....*/
}
```