Reputation: 1
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int LordIronhead = 0;
char answer;
cout<<"Is Lord Ironhead present? Y/N.\n";
cin >> answer;
if (answer == 'Y')
{
LordIronhead=0;
}
else if (answer == 'N')
{
LordIronhead= LordIronhead+1;
}
cout<< ""<<LordIronhead<<"\n";
system("PAUSE");
return 0;
}
Every time I run the program and If I answer NO (N) the result is always 0 instead of 1 (LordIronhead = LordIronhead + 1)
May I know where my error is?
Upvotes: 0
Views: 107
Reputation: 42175
Your code is correct but is sensitive to the case of user input (it treats user input of N
and n
differently). You'd remove a possible source of user confusion by converting the input to a known case before checking it. You can do this using either toupper or tolower
cin >> answer;
answer = toupper(answer);
Upvotes: 3
Reputation: 498
Better using 1 and 0 instead of N and Y. Its more recognizable to the system
Upvotes: 0
Reputation: 11
I just tried this myself and found that if I answered N I got the expected answer (1). If I hit n, however, it came back as 0. Are you sure you're hitting N and not n?
Upvotes: 1
Reputation: 36049
Your code is fine in principle, but you might run into issues with the two-valued logic of 'answer' being checked against 'Y' and against 'N' with no fall-through case. I suspect you are running into EOL or case or character conversion issues, falling through both if's and thereby never changing the Lord.
For showing the problem, try an else statement:
else if (answer == 'N')
{
LordIronhead= LordIronhead+1;
} else {
std::cout << "Invalid answer '" << answer << "'" << std::endl;
}
Upvotes: 3