Counting specific character in multiple strings

Oct 14, 2014 at 4:14am
I am trying to write a program that counts the amount of occurrences the letter 'b' appears in every string i type and hit enter. And will display it after i enter the word stop. As of now it keeps displaying zero.

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

using namespace std;

int main()
{
	int count=0;
	string str1;
	char inChar;


	cout << "Enter a word: ";
	getline(cin,  str1);
	while(str1!="stop")
	{
		cin.get(inChar);
			
			while (inChar != '\n')
			{
			if(inChar == 'b')
				count++;
			cin.get(inChar);
			}
			cout << "Enter a word: ";
			getline(cin, str1);
	}
	cout << count;

	system("pause");
}
Oct 14, 2014 at 4:43am
1
2
3
for(auto it = str1.begin(); it != str1.end(); ++it)
  if((*it) == 'b' || (*it) == 'B')
    count++;

:p
Oct 14, 2014 at 5:05am
i wish it were that easy. we haven't learned that far in class. All we have basically done are if statements and while loops. Plus all the preceding obvious stuff. No arrays or vectors either:(
Oct 14, 2014 at 5:17am
1
2
3
4
5
6
7
while (getline(cin, str1)) {
    for (int p = 0; p < str1.length(); p++) {
        if (str1[p] /*fill in the rest*/) {
            /* you decide what goes here */
        }
    }
}


http://www.cplusplus.com/reference/algorithm/count/
http://www.cplusplus.com/reference/numeric/accumulate/
Oct 14, 2014 at 5:32am
I haven't learned for statements yet.
Oct 14, 2014 at 6:27am
>_>
This is exactly the same as a for loop:
1
2
3
4
5
6
int i = 0;
while(i<max)
{
  //...
  i++
}
Topic archived. No new replies allowed.