Simple for loop program help

Hello! I am writing a program called "Vote Count" for class practice. It is problem two on this link:

http://www.cemc.uwaterloo.ca/contests/computing/2014/stage%201/juniorEn.pdf

My problem is that whenever I input an even number and I have try to make it a Tie, it always input a letter. for example, I input: "A, A, A, B, B, B" and I get "B" as the answer instead of "Tie". What is the problem? Thanks in advance!

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
46
  #include <iostream>
#include <iomanip>
#define _USE_MATH_DEFINES		
#include <math.h>
#include <string>               
using namespace std;

int countSubstring(const string& str, const string& sub)
{
	if (sub.length() == 0) return 0;
	int count = 0;
	for (size_t offset = str.find(sub); offset != std::string::npos;
	offset = str.find(sub, offset + sub.length()))
	{
		++count;
	}
	return count;
}

int main()
{
	int NumofVotes;
	cin >> NumofVotes;
	string input;
	int A = 0, B = 0;

	//must use getline to input entire line
	for (int AmountofTimes = 0; AmountofTimes <= NumofVotes; AmountofTimes++)
	{
		getline(cin, input);
		
	}
	
	A = countSubstring(input, "A");
	B = countSubstring(input, "B");
	
	

	if (A == B)
		cout << "Tie";
	else if (A > B)
		cout << "A";
	else
		cout << "B";

}//end main 
What did you enter for the number of votes?

Do you realize that your count function will only count the last entry?

@jib

I entered 6 as mt number of votes.

Really? Then how do I fix it then. I'n not so sure on what to do.
Can you elaborate/explain it in similar terms. The links you gave me were kind of confusing. Sorry.
Hi,

This works for a char:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    const std::string MyString = "abcasdfafghabcrty";
    const char CharSearch = 'a';

    std::size_t Count = std::count(MyString.begin(), MyString.end(), CharSearch);
    std::cout << "Count is " << Count << '\n';
    return 0;
}


I found this on SO:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string>
#include <iostream>

int Count( const std::string & str, 
           const std::string & obj ) {
    int n = 0;
    std::string ::size_type pos = 0;
    while( (pos = obj.find( str, pos )) 
                 != std::string::npos ) {
    	n++;
    	pos += str.size();
    }
    return n;
}

int main() {
    std::string s = "How do you do at ou";
    int n = Count( "ou", s );
    std::cout << n << std::endl;
}
Topic archived. No new replies allowed.