voting program



Im new at cpp and i try to train myself with a little voting program. You give in the parties and then the votes of the party.

#include<iostream>
#include<string>

using namespace std;

int main()
{
string sInput = " ";
string sName1 = " ";
string sName2 = " ";
int iParty1 = 0;
int iParty2 = 0;

cout << "Name of the first party: ";
cin >> sName1;
cout << "Name of the second party: ";
cin >> sName2;

while (sInput != "")
{
cout << "Your vote: ";
cin >> sInput;
cout << endl;
if (sInput == sName1)
{
iParty1++;
}
else
{
if (sInput == sName2)
{
iParty2++;
}
else
{
cout << "Wrong Input" << endl;
}
}

}
cout << sName1 << ": " << iParty1 << endl;
cout << sName2 << ": " << iParty2 << endl;
getchar();
return 0;
}

So you see the while loop. I want the program stop if i only press enter. But when i do it nothing happens. Why? Give me a clue!
You need to use cin.getline() if you want a sense of a blank line.

cin >> sInput; just ignores all white space (and that includes newlines).
Last edited on
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
47
#include<iostream>
#include<string>

using namespace std;

int main()
{
string sInput = " ";
string sName1 = " ";
string sName2 = " ";
int iParty1 = 0;
int iParty2 = 0;

cout << "Name of the first party: ";
cin >> sName1;
cout << "Name of the second party: ";
cin >> sName2;

cin.ignore();

while (sInput != "")
{
cout << "Your vote: ";
getline(cin, sInput);
cout << endl;
if (sInput == sName1)
{
iParty1++;
}
else
{
if (sInput == sName2)
{
iParty2++;
}
else
{
cout << "Wrong Input" << endl;
}
}

}
cout << sName1 << ": " << iParty1 << endl;
cout << sName2 << ": " << iParty2 << endl;
getchar();
return 0;
}
Topic archived. No new replies allowed.