I am working on a program that counts the votes of N candidates and print the winner and votes received. Here is the input format:
The input begins with a positive integer M which indicates the number of cases to process. Each case starts with a number N which indicates the total number of candidates in that case. This is followed by N candidate names, occupying one line each. This is followed by the total number of ballots B, which is then followed by B ballots. Each ballot is actually a number from 1 to N. A value 1 indicates a vote for the first candidate, 2 for the second candidate, and so on.
For example:
1
3
Mark Zuckerberg
Larry Page
Steve Jobs
15
2 1 2 3 2 3 3 1 1 1 2 3 3 3 1
The output should look like this:
Election #1 :
Steve Jobs (6)
My problem is getting the candidate names. I used getline(). Here's my code snippet:
cin >> M;
int N;
while (idx < M)
{
cin >> N;
int i = 0;
string candidate[N];
while (i < N)
{
getline(cin, candidate[i]);
i++;
}
cin >> ballot;
i = 0;
int vote[ballot];
while (i < ballot)
{
cin >> vote[i];
i++;
}
process(N, candidate, ballot, vote, idx+1);
idx++;
}
When I tried the sample input above, it resulted into this (I used input redirection in command prompt and wrote the input on a file):
Election #1 :
0x22fe20 (2147344384)
I tried to print the candidate name that was read for every iteration so I can get a hint of what's wrong and it seems that only the first two names were read and the output was printed immediately, resulting into a wrong one. I guess the other values succeeding it were not read, that's why.
Test
1 2 3 4 5 6
while (i < N)
{
getline(cin, candidate[i]);
cout << candidate[i] << endl;
i++;
}
Test Output
Mark Zuckerberg
Larry Page
Election #1 :
0x22fe20 (2147344384)
What could be the problem in here? I'm guessing it's in the getline() part. How can I fix it? Any suggestions? Thanks a lot.