C++ setGender method reverts to default values - c++

I've written the code bits below. I have a constructor which takes five arguments. Unfortunately, the setGender method spits out a default 'M' for all instances of a class rather than setting the gender to the specified parameter. What am I doing incorrectly? Any advice would be greatly appreciated. Thank you.
DateProfile::DateProfile(char gdr,
char searchGdr, int romanceScale, int financeScale, string theName)
bool DateProfile::setGender(char gdr)
{
if (gdr != 'M' || gdr != 'F')
return false;
gender = gdr;
return true;
}

if (gdr != 'M' || gdr != 'F') is always true, irrespective of input. If you're passing 'M', the second part of the expression is true. If you're passing anything else, the first part of the expression becomes true.
What you meant to write is if (gdr != 'M' && gdr != 'F') instead.
Increasing the warning level of your compiler may have helped you spot the error. Most compilers will warn about expressions always evaluating to a single value, or at least about the unreachable code following it.

Related

Infinite Loop When Using Function Return Value as a Statement [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 5 years ago.
Was making a small code for a text based game but i tried to do thinks a bit different than the tutorial sort of to test my understanding but i tried to get a function value to make a do while statement but it seems whether the statement false or true the code just keep looping infinitely im a beginner so pls if you have a time explain why the code is faulty and Thank you in Advance
The main function
int main() {
PrintIntroStart();
do {
PlayGame();
AskToPlayAgain();
} while (AskToPlayAgain() == true);
return 0;
}
the Bool Function
bool AskToPlayAgain(){
//Asking The Player Whether To Play Again Or Not
std::string PlayerResponse = "";
std::cout << "Do You Want To Play Again? (Yes/No)" << std::endl;
std::cin >> PlayerResponse;
if (PlayerResponse[0] == 'y' || 'Y')
return true;
else
return false;
}
Also, here you are asking twice to play again
do {
PlayGame();
AskToPlayAgain();
} while (AskToPlayAgain() == true);
this should be
do {
PlayGame();
} while (AskToPlayAgain() == true);
if (PlayerResponse[0] == 'y' || 'Y') this one should be
if (PlayerResponse[0] == 'y' || PlayerResponse[0] == 'Y')
Otherwise your if condition is always true, because 'Y' itself is non-zero.
And in fact you don't need this if statement, just
return PlayerResponse[0] == 'y' || PlayerResponse[0] == 'Y';
So first of all, you are only checking the outcome of the game every second play.
You should follow #ziza s answer and remove the function call inside the loop.
The second problem, that causes the infinite loop is your input check.
A bool value in c++ is not a single bit, but just anoter regular value that is evaluated as false if it is 0 and to true if it has any other value. In your case the first comparison will evauate to 1 if the player input is 'y' and the second part of the condition will be the value of the 'Y' character (which is not 0). So your condition will always be true like #liliscent stated.

Simple Word Guessing Game

bool guess(char c)
{
if (guesses[c])
{
guesses[] = c;
return true;
}
else if (c > ='a' && c <= 'z')
{
guesses[] = c;
return false;
}
}
bool guesses[255] = {};
I need to use this to see if the person has enter a char between a - z and if they haven't I return true else I will return false. either way I will also update guesses with the char. Right now I don't understand how to add char to the array, so that next time I check the it will be false and tell them it was already guessed. I understand this is using the ASCII table but beyond that I am lost. Could anyone explain why this won't work.
I currently get the error
expected primary-expression before']'
but if I take bracket out I get
incompatible type char to bool
which make sense but then how do I make it so where char c is will be mark true in the Boolean array
You've left your brackets empty, so you currently aren't providing an index:
guesses[c] = c;
But you also don't want to assign the char to guesses, you'd want to assign a bool:
guesses[c] = true;
That will compile* and fix your problem.
* Note you also have a syntax error with > =, which I assume was just a copy+paste issue from the editor to the question, but you should fix that also to be >=. Your function guess can also potentially not return (if neither the if or else if are true), which is undefined behaviour. You should ensure all control paths return a value, and you should make sure you compile at the highest warning level so you are warned about these things.
But not your design.
Since you're only dealing with characters a-z, you don't need to allocate all 255 elements like you do. You could simply minus the character to obtain the correct index:
bool guesses[26];
if (c >='a' && c <= 'z')
guesses[c-'a'] = true;
Consider instead using a std::set, a container of unique elements, to track whether a character has been pressed:
#include <set>
std::set<char> guesses;
bool guess(char c)
{
// Have we already inserted this character?
if (guesses.find(c) != std::end(guesses))
{
// Character has already been guessed:
std::cout << "This character has already been guessed";
return true;
}
else if (c >= 'a' && c <= 'z')
{
// Valid guess:
guesses.insert(c);
return false;
}
}

if statement with multiple condition not working...

here is my code :
string function1( string input)
{
string output;
int i=0;
if (input.at(i)!='A' || input.at(i)!='a'|| input.at(i)!='E' || input.at(i)!='e' || input.at(i)!='I' || input.at(i)!='i' || input.at(i)!='O'||input.at(i)!='o' || input.at(i)!='U' || input.at(i)!='u')
{
char x=input[i];
input.erase(input.begin()+i);
output=input+x;
}
else
{
output=input+"yay";
}
return output;
}
but its not doing what i want it to do.. can't figure out where its going wrong...
can any1 help?
Basically the issue is that its never going in to the else statement..
if i pass in BJ it should return BJYAY right..
but its giving me JB
Thanks!
Change the || operators of the if statement to &&. The statement you have written is always true. What you want is that the first character is not a vowel, i.e. it does not match 'A' AND it does not match 'E', etc.
Changing the != to == will give you the result requested.

if condition on turbo C++

I'm having a problem regarding with if statement in C++ this statement is in do-while loop.
gotoxy(27,22);cout<<"Do you want to continue [Y]?";
sub=getche();
if(sub!='y' || sub!='Y')
{
gotoxy(27,24);cout<<"INVALID ANSWER!!";
gotoxy(27,26);cout<<"Closing Program....";
delay(3000);
exit(1);
}else
{
sub=ans;
}
}while(tolower(ans)=='y');
whenever I input y on the variable sub the code on if statement is still executing.. please someone tells me where is the error.. Thanks!
The boolean expression of (sub!='y' || sub!='Y') will always evaluate to true
This line:
if(sub!='y' || sub!='Y')
Needs to be this:
if ( (sub != 'y') && (sub != 'Y') )
Your code if(sub!='y' || sub!='Y') will be true ,no matter what you enter because eithersub!='y' or sub!='Y' will evaluate to true. Hence Use && instead of ||.

reference to array, not quite working as intended

Greetings,
Since my last question about C++, I actually learned quite an amount. I am now comfortable with classes, just not so comfortable with pointers and references yet.
Please note, I am not asking you nesceserally to solve my problem, I'm asking why I'm not getting the wished result.
here are some code snippets that that should help me explain the problem:
Im making a console based tic-tac-toe game(recently started learning C++, this imo is a good way for it)
main.cpp:
//Here I initalise 1 variable and an array
int move;
char board[9] = {' ',' ',' ',' ',' ',' ',' ',' ',' '};
First question: Is there a better way to define empty spaces in a char array?
The reason i'm doing it like this is, I want my tictactoe board to contain an empty space when an X or O has not been set yet.
main.cpp:
if(referee.validateMove(board, move))
{
board[move] = player2.getToken();
displayBoard(board);
}
What happens here is easily understood but i'll explain anyway;
A call to the validateMove method from the object referee is made, and passed 2 paramaters, the move that the player has selected (in between 0-8). and the tictactoe board.
Referee.cpp
bool Referee::validateMove(const char (&board)[9], int& move)
{
if(board[move] != 'X' || 'O')
{
return true;
}
else
{
return false;
}
}
Here is where the main trouble is, and my last question arises.
As seen before, I passed an array of chars with a size of 9.
The reference to the move variable works well(should i use a reference or pointer?) and it contains the wished result.
At this point, say player 1 just made its move and placed a token in position 2
I now want to place my token as PLAYER 2 on position 2
When I debug with visual studio, I get the following:
0x0024faa8 " O ÌÌÌÌÌÌÌÌÌÌÌ"
This is when i hold my mouse on the board parameter.
So the board does know, it is occupied.
Why however does the validateMove method always return true, and is board[move] never equal to O or X?
Thank you for taking the time to read my problem. If you have a question, or I explained something in a stupid matter, you see invalid naming conventions, please notify me. I am a student, and I want to pick up as much as possible.
This problem is resolved. Thanks for those who have answered. Highly appreciate it.
Your condition boils down to this:
if((board[move] != 'X') || ('O'))
'O' will always evaluate to true in this case, so you always pass the condition. What you want is this:
if((board[move] != 'X') && (board[move] != 'O'))
To verify, this code runs fine for me:
#include <iostream>
bool validateMove(const char (&board)[9], int move)
{
if((board[move] != 'X') && (board[move] != 'O'))
{
std::cout << "True" << std::endl;
return true;
}
else
{
std::cout << "False" << std::endl;
return false;
}
}
int main()
{
char board[9] = {' ',' ','O',' ','X',' ',' ',' ',' ',};
validateMove(board, 0);
validateMove(board, 2);
validateMove(board, 4);
}
The output is:
True
False
False
The reason you're displaying extra junk at the end is that your
"board" isn't a nul terminated string. If you also want to use
it for display purposes, you'll need to declare it board[10],
and add a '\0' at the end. From a design point of view,
however, I would recommend against this. I would, in fact,
define a Board class, with a << operator to display it, so that
I could change the representation at will, without having to
modify the framework. If the representation within the board
class is a char[9], and the board values are the actual
characters, then you could simply memcpy the board into
a char[10], append the missing '\0', and output that. Be ready
to adopt a more complex solution later, however, if you find
that char[3][3] is a better representation, or that it is
preferable to use, say 0, -1 and 1 as the status of a position
on the board. (I'd probably have the board class responsible
for determining the legality of a move, too.)
And while I'm at it: your validateMove function should be:
return board[move] == 'X' || board[move] == '0';
or perhaps even simpler:
return board[move] == ' ';
You were ||'ing with '0', which, converted to bool, is always
true. And an if which returns true or false is unnecessary
complication and clutter, and suggests that the author either
doesn't understand the concept of 'bool', or is intentionally
trying to obfuscate the code.