Yuudoku
Yuudoku

Reputation: 1

Refine my code/program where did I go wrong?

#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

Answers (4)

simonc
simonc

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

Eveli
Eveli

Reputation: 498

Better using 1 and 0 instead of N and Y. Its more recognizable to the system

Upvotes: 0

user685912
user685912

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

thiton
thiton

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

Related Questions