I am teaching myself c++ and am building a simple menu program. Im a complete noob to C++ so I apologize in advance for the question if it seems foolish. My code continuously calls getNum() and never exits, despite the correct menu selections. What am I doing wrong? Here is my code:
#include <iostream>
#include <string>
using namespace std;
void calc();
void pass();
string getNum(string num);
int main(int argc, const char * argv[])
{
string num = "0";
string menu = "Enter... \n 1 For calculator \n 2 for Passwords";
cout << "Hello this is a sample menu program" << endl;
while(num != "1" || num != "2")
{
getNum(num);
cout << "You selected: " << num << endl;
}
if(num == "1"){
calc();
}
else {
pass();
}
}
void calc() {
cout << " You are running the calculator" << endl;
}
void pass() {
cout << "You are running passwords" << endl;
}
string getNum(string num) {
cout << "What would you like to do?" << endl;
cout << "Enter... \n 1 For calculator \n 2 for Passwords" << endl;
getline(cin, num);
return num;
}
Change this condition
while(num != "1" || num != "2")
to
while(num != "1" && num != "2")
To write the condition correctly you should consider that the loop should not be repeated if num either equal to "1" or "2". This condition can be written as
num == "1" || num == "2"
However the loop shall be repeated if this condition is not true. So the condition for the loop will be repeated will look like
! ( num == "1" || num == "2" )
According to the mathematical logic this condition is equivalent to
num != "1" && num != "2"
It would be better to rewrite the loop like
string num;
//...
do
{
getNum(num);
cout << "You selected: " << num << endl;
} while ( num != "1" && num != "2")
At least one iteration should be done in any case should not it?
Also define the function as
void getNum(string &num);
//...
void getNum( string &num) {
cout << "What would you like to do?" << endl;
cout << "Enter... \n 1 For calculator \n 2 for Passwords" << endl;
getline(cin, num);
}
getNum(num);
In getNum you have a return statement that returns what the user entered. When you call getNum you don't save that return value.
num = getNum(num);
To make things clearer, I would remove the input parameter from getNum. You don't need to pass anything to it since it's job is to prompt for a number and return that number.
string getNum() {
cout << "What would you like to do?" << endl;
cout << "Enter... \n 1 For calculator \n 2 for Passwords" << endl;
string num;
getline(cin, num);
return num;
}
Then change the call to:
num = getNum();
Another issue is your loop condition.
while(num != "1" || num != "2")
Think about what this will do if num were, say, "1". You'd want the loop to stop, right? Look what happens if we evaluate and reduce the expression bit by bit:
while(num != "1" || num != "2")
while("1" != "1" || "1" != "2")
while(false || true)
while(true)
Well that's not right. It should have evaluated to false. The || should be &&.
while(num != "1" && num != "2")
Line
while(num != "1" || num != "2")
be DeMorgan laws is the same as
while(!(num == "1" && num == "2"))
So you need
(num == "1" && num == "2")
to be true
Hence the difficulty
apart from the other bits of the code that are in error
You have written while(num != "1" || num != "2")
so either num would be equal to "1" or "2" or none of these. In any condition one of these condition is true( i.e. either num is not equals to 1 , this is true or num is not equals to 2 , this is true), therefore your while loop is always true and continuously run without stop
this condition
while(num != "1" || num != "2")
will always return true for all inputs. for example, "1", it is false on num != "1" but will still return true on the other condition num != 2, thus it will never exit (true || false == true)
also it should be
else if(num == '2') {
pass();
}
correct condition should be while(!(num != "1" && num != "2")) to only allow "1" and "2" inputs
Related
basically I am having weird trouble with my while loop near the beginning of the program which checks for user validation on their choice of activity. When they choose the first activity and complete it, it works fine, but when they complete the second activity, it will go into runtime and keep requesting the user to input a valid choice, even though they haven't even gotten the chance to input a choice. Any tips?
#include <iostream>
using namespace std;
int main()
{
const int DIGITS_CHOICE = 1, IDENTIFIER_CHOICE = 2, DOUBLE_CHOICE = 3, EXIT_CHOICE = 4;
int choice;
int userNumber, storedNumber, factor = 10, digitCounter = 0, subtractor;
char ch;
do
{
cout << "\n\n\t\tPlease choose an option:\n\n"
<< "1. How many digits?\n"
<< "2. Is this a valid C++ Identifer?\n"
<< "3. Is this a double letter word?\n"
<< "4. Exit\n";
cout << endl << "Choice: ";
cin >> choice;
while (choice < DIGITS_CHOICE || choice > EXIT_CHOICE)
{
cout << endl << "Please enter a valid menu option: ";
cin >> choice;
}
if (choice != EXIT_CHOICE)
{
switch (choice)
{
case DIGITS_CHOICE:
cout << "Please enter an integer: ";
cin >> userNumber;
storedNumber = userNumber;
if (userNumber < 10)
{
digitCounter = 1;
}
else
{
while (userNumber != 0)
{
subtractor = userNumber % factor;
if (subtractor > 0)
{
userNumber = userNumber - subtractor;
factor *= 10;
digitCounter++;
}
else
{
userNumber = 0;
}
}
}
cout << storedNumber << " has " << digitCounter << " digit(s)." << endl;
factor = 10;
digitCounter = 0;
break;
case IDENTIFIER_CHOICE:
cout << "Please enter an identifier and press [Enter] immediately after. ";
cin >> ch;
if (ch >= 0 || ch <= 9 || ch <= 'a' || ch >= 'z' || ch <= 'A' || ch >= 'Z' || ch != '_')
{
if (ch >= 0 || ch <= 9)
{
cout << "Not a valid identifier." << endl;
cout << "Identifiers cannot start with a digit." << endl;
ch = '\n';
}
else
{
cout << "Not a valid identifier." << endl;
cout << "Inavlid character." << endl;
ch = '\n';
}
}
while (ch != '\n')
{
if (ch >= 'a' || ch <= 'z' || ch >= 'A' || ch <= 'Z')
{
cin.get(ch);
}
}
break;
case DOUBLE_CHOICE:
break;
}
}
} while (choice != EXIT_CHOICE);
return 0;
}
Also the program isn't complete yet. the third option has nothing and the 2nd option is almost complete. the first activity though is complete :)
Your check for valid characters is too broad, and doesn't really make sense:
if (ch >= 0 || ch <= 9 || ch <= 'a' || ch >= 'z' || ch <= 'A' || ch >= 'Z' || ch != '_')
Every possible value of ch is going to be greater than or equal to zero, so this expression is equivalent to (true || a || b || c || ... || z) and it's always going to resolve to true.
Instead, see if it's below 'A', between 'Z' and 'a' or beyond 'z' and if so, it's invalid.
Also, when checking if it's a digit, you need to check if it's ≥ '0' and ≤ '9' as characters. It's important that you compare it to the character representation of 0 and 9 because the value of the character '0' not actually 0 (it turns out it's actually 48) and likewise with '9':
if ( ch < 'A'
|| (ch > 'Z' && ch < 'a')
|| ch > 'z')
{
if (ch >= '0' && ch <= '9')
{
cout << "Not a valid identifier." << endl;
cout << "Identifiers cannot start with a digit." << endl;
ch = '\n';
}
else
{
cout << "Not a valid identifier." << endl;
cout << "Invalid character." << endl;
ch = '\n';
}
}
It's not really clear what the check after that is meant to do? Is it only meant to allow letters? That seems strange after saying "Identifiers cannot start with a digit." anyway:
if (ch >= 'a' || ch <= 'z' || ch >= 'A' || ch <= 'Z')
This has essentially the same issue where every character is going to be either above 'a' or below 'z' or both, so this will always resolve to true. Instead, use && to check for being within a range:
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
Hopefully that addresses your question.
The logic is not great; i is valid, but your code says it's not. It at least goes back to the menu just fine. Your code is also behaving like it will respond immediately as letters are being typed. That is not the case. It won't print anything until the user presses Enter.
It seems the issue is your variable ch being a char. If I type anything that's longer than a single character, what will happen is that the single character gets evaluated, and the remaining characters I typed remain in the input stream. It looks like you are attempting to handle that, but it's not working. I am not going to spend time delving into the why, partly because it's complex, partly because I don't know the full intricacies of istream behavior.
What I will say is that if you want to handle a multi-character input, use cin.get() everywhere and not just sometimes. You can do processing of each character, but again, nothing will go to the screen until the user presses Enter.
But here's code that appears to work:
#include <cctype> // isalpha() and isalnum()
#include <string> // ch is now a std::string
// ...
case IDENTIFIER_CHOICE:
cout << "Please enter an identifier and press [Enter] immediately after. ";
std::cin.ignore(256, '\n'); // needed because of getline behavior
std::getline(std::cin, ch);
if (!(isalpha(ch[0]) || ch[0] == '_')) {
cout << "Not valid.\n";
break;
}
for (int i = 1; i < ch.size(); ++i) {
if (!isalnum(ch[i])) {
cout << "Not valid.\n";
break;
}
}
cout << "Valid.\n";
break;
// ...
With cin, when you press Enter, that keystroke is saved in the input stream. getline() doesn't behave the way we expect because while cin will typically ignore that keystroke, getline does not. So I just tell cin to ignore an arbitrary (but sufficient in this case) amount of characters in the stream up to and including the Enter keystroke (Mac and Linux, should still behave for Windows (I think)).
This is still far from bulletproof input validation (that's impossible), but I think it suffices for what you're working on.
I'm a student, and I am currently working on C++ Classes. I am making a program which is supposed to ask a user to input a float point number not greater that 99.99 as a price of fuel at a gas station. I have created code that saves the user input in to a char array, and created limits so that the user can't input more than 2 dots, for example (2..2). The maximum number of characters is 5 including one dot. Now, everything works fine except for if the user enters two sets of strings before hitting enter. I have a problem because the second string messes up with other cin statements in the loop.
The code will also take the finalized char array input, and than covert it to a float variable so that the further calculations can be computed easily.
I am working on a Windows system, and Visual Studio 2017 C++.
I have tried detecting the single white space in an if/else statement, but it seems that white space is not detected as a single char array member, like this ex. else if (str[count] == ' ') , and than asking to re enter the correct input without the white space. getline() function could not work on a char array, so I couldn't discard the characters entered after including and after the white space in this way. I have tried changing the char array to a string, but still if the user inputs two or more strings separated by white space, my program keeps reading it in to cin over again.
int main()
{
int count = 0;
int lenFlag = 0, mainFlag = 0;
float result = 0;
int len;
char str[6] = "00000";
//string str ="00000";
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
//This part will ask the user to set the price of fuel
//for the gas pump program. The programming project segment
//is from a book by Walter Savitch "Absolute C++".
while (mainFlag == 0)
{
cout << "Please enter the fuel price in dollars $";
cin >> str;
len = strlen(str);
cout << "strlen is = " << len << endl;
while (len <= 5 && mainFlag == 0)
{
count = 0, lenFlag = 0;
while (count < len && lenFlag == 0)
{
if (count == 0 && (str[count] < 48 || str[count] > 57))
{
cout << "The first input member must be a number."
"You must use a number between 0-9.\n"
"Try again: ";
cin >> str;
len = strlen(str);
lenFlag = 1;
}
else if (count > 0 && (str[count] < 48 || str[count] > 57)
&& str[count] != '.')
{
cout << "You must enter number between 0-9, or a decimal delimiter.\n"
"Try again, : ";
cin >> str;
len = strlen(str);
lenFlag = 1;
}
else if (count > 0 && (str[0] == '.' && str[1] == '.') || (str[0] == '.' && str[2] == '.') ||
(str[0] == '.' && str[3] == '.') || (str[0] == '.' && str[4] == '.') ||
(str[1] == '.' && str[2] == '.') || (str[1] == '.' && str[3] == '.') ||
(str[1] == '.' && str[4] == '.') || (str[2] == '.' && str[3] == '.') ||
(str[2] == '.' && str[4] == '.') || (str[3] == '.' && str[4] == '.'))
{
cout << "You have entered more than 1 decimal delimiter, try again: ";
cin >> str;
len = strlen(str);
lenFlag = 1;
}
else if (count > 1 && str[0] > 48 && str[0] < 58 && str[1]>47
&& str[1] < 58 && str[2]>47 && str[2] < 58)
{
cout << "Maximum number is 99.99, try again:\n";
cin >> str;
len = strlen(str);
lenFlag = 1;
}
else if (str[count] == ' ')
{
cout << "Typing whitspace is not an option!!" << endl;
cout << "Try again!!" << endl;
cin >> str;
len = strlen(str);
lenFlag = 1;
}
else if (count == len - 1 && lenFlag == 0)
{
//cout << "Main flag switches to 1!!" << endl;
mainFlag = 1;
}
count++;
}
} //while(lenCopy <= 5) loop end
if (len > 5)
{
cout << "Either non-numbers were entered, or a negative
number, or an incorrect " << endl;
cout << "number size. Enter a maximum size of 5
including a .dot for decimal number" << endl;
cout << "Maximum number is 99.99." << endl;
mainFlag = 0;
}
}//mainflag loop ends
int dotpos = 0;
for (int n = 0; n < len; n++)
{
if (str[n] == '.')
{
//dotpos = n + 1;
dotpos = len - n - 1;
cout << "dotpos = " << dotpos << endl;
}
else
{
result = result * 10 + (str[n] - '0');
//Line above is a float and character mix as a math equation.
cout << "result " << n << " = " << result << endl;
}
}
if (dotpos > 0)
result = result / (power(10, dotpos));
cout << "You have set the cost at $" << result << " per gallon." << endl;
system("pause");
return 0;
}
Occasional stack around str variable has been corrupted, and that happens when I heavily try to mess with the user input just to check if the program can crash. That's why I need to know how to clear the input after the white space. I solved the stack corruption problem by changing the char array to string, but still not the excess characters that potential users might throw down at the program.
If you must use character arrays, I highly recommend restricting the amount of characters read from the console.
The std::istream::getline() is well suited for this:
const unsigned int LIMIT = 10;
char number_as_text[LIMIT];
std::cout << "Enter a floating point number, less than 10 characters: ";
std::cin.getline(number_as_text, LIMIT);
You can then use a function like strtod to convert the string to floating point variable.
I have found one good way to solve a problem of the string buffer overflow. It uses
cin>>ws; followed by getline() function. The two need to be used in conjunction, and
than the read will be only the first string of characters and everything after the whitespace will be trashed.
cout << "Do you want to set cost in gallons or liters? "
"\nPress G for gallons or L for liters: ";
cin >> ws;
getline(cin, chooseSetCost);
while (chooseSetCost != "G" && chooseSetCost != "g" && chooseSetCost != "L" && chooseSetCost != "l")
{
cout << "Incorrect input. Try again: ";
cin >> ws;
getline(cin, chooseSetCost);
cout << "choose cost is = " << chooseSetCost << endl;
}
I'm trying to do a simple game Guess Number and created a while condition to do that, but I want to insert a question to play again if the player type "Y" on the queue or close the window if the player type "N". My way is not working and I didn't find a solution for this problem.
int main()
{
int guess, number;
char again;
srand(time(0));
number = rand() % 1000 + 1;
while (guess != number)
{
std::cout << "Enter the number guess between 1 and 1000: ";
std::cin >> guess;
if (guess < number)
{
std::cout << "Is more than this" << std::endl;
}
else if (guess > number)
{
std::cout << "Is less than this" << std::endl;
}
else if (guess < 1)
{
std::cout << "The value to guess is between 1 and 1000" << std::endl;
}
else if (guess > 1000)
{
std::cout << "The value to guess is between 1 and 1000" << std::endl;
}
else
{
std::cout << "This is the number" << std::endl;
std::cout << "Do want play again? [Y/N ]" << std::endl;
std::cin >> again;
if (again == 'N' || again == 'n')
{
break;
}
else if (again == 'Y' || again == 'y')
{
continue;
}
}
}
When you correctly guess the number, your while condition becomes false and hence the loop exits (i.e. guess becomes equal to number, and hence the condition guess != number is false). Try changing to condition of the while loop.
char again = 'Y';
while (again == 'Y' || again == 'y') { ... }
Starting with some presumably yet unrecognised problem: You won't reach all of your if branches:
if (guess < number)
{ }
else if (guess > number)
{ }
// now if you really get to the following else, guess was neither
// smaller nor greater than number, i. e. is EQUAL!
else if (guess < 1)
{ /* won't ever be entered as number(!) is never < 1 (be aware: guess == number) */ }
else if (guess > 1000)
{ /* won't ever be entered as number is never > 1000 */ }
else
{ }
You can solve in two variants, by moving the unreachable checks either in front of the initial ones:
if (guess < 1)
{ }
else if (guess > 1000)
{ }
else if (guess < number)
{ }
else if (guess > number)
{ }
else
{ }
or into them:
if (guess < number)
{
if (guess < 1)
{ }
else
{ }
}
else if (guess > number)
{
if (guess > 1000)
{ }
else
{ }
}
else
{ }
Now to the actual problem, let's consider the else:
// be aware that guess == number now!
if (again == 'N' || again == 'n')
{
break; // fine so far...
}
else if (again == 'Y' || again == 'y')
{
continue;
// re-enters the loop - be aware that the condition is still checked!!!
}
// and if none of all was entered???
// as is, we'd just go on with the loop body - as this was the last statement,
// though, the loop will be re-entered by checking the condition; i. e. if
// getting here, we do effectively exactly the same as in the second if check
// above...
OK, so you (implicitly) defined a default of 'y'. You then could just simply remove the second if (else if == y) and nothing would change.
However, the loop condition is not true any more (guess == number still applies!). Easiest now: just make an endless loop of:
for(;;)
{
if(again == 'n')
break;
// obsolete, just drop it:
//if(again == 'y')
// continue;
}
I personally, though, would rather have the 'n' as default (so typing 'x', 'q', 'a' all result in exiting as well), so I'd rather have:
for(;;)
{
if(again != 'y' && again != 'Y')
break;
}
I'm nearly finished working on a small guessing game, but i have run into a problem I don't know how to work around.
The problem is with the check_guess function that is checking to make sure the guess being input is a number between 1 and 100.
When running the program the first time, everything works fine.
http://i.imgur.com/pprunDT.png (I would post images if my reputation weren't so low)
But every time after, where yes to play again is chosen, the program runs through the check_guess function and displays "Invalid Input" when it shouldn't
http://i.imgur.com/8OSnSJt.png
I'm not sure why the program is behaving this way.
The code for the entire program is here:
#include <iostream>
#include <cstdlib> //for rand
#include <ctime> //for time
#include <string>
#include <sstream> //for conversions from string to int
using namespace std;
int check_guess(int tries) { //function for limiting the input of guess
string guess = "";
int result = 0;
do {
getline (cin, guess);
istringstream convert(guess);
if ( !(convert >> result) || (result < 1 || result > 100) ) {
result = 0;
cout << "Invalid Input.\n" << endl;
cout << "You have " << tries << " tries: ";
}
} while (result == 0);
return result;
}
bool play_again() { //function for limiting the input of mode
bool quit;
string yn;
do {
cin >> yn;
if ( yn == "y" || yn == "yes" ) {
quit = false;
}
else if ( yn == "n" || yn == "no" ) {
quit = true;
}
else {
yn = "invalid";
cout << "Invalid input.\n\nEnter 'y' or 'n': ";
}
} while ( yn == "invalid" );
return quit;
}
int main()
{
srand(time(0)); //sets seed to be random
int mystery = 0; //defines mystery number
int guess = 0; //defines guess
int tries = 5; //defines trys
bool quit = false; //defines replay or quit
cout << "----------------------------------\n";
do { //while mode is not set to quit, keep playing
tries = 5; //resets tries each new game
mystery = rand() % 100 + 1; //sets mystery number to be random
guess = 0;
cout << "Pick a number between 1 and 100.\n\nYou have 5 tries: ";
while (tries != 0) { //loops until you have no tries left
guess = check_guess(tries);
if (guess == mystery) { tries = 0; } //if you guess right it ends the loop
else { tries--; } //guessing wrong lowers tries by 1
if ( tries != 0 && guess > mystery) {
cout << guess << " is too high.\n" << endl;
cout << "You have " << tries << " tries: ";
}
if ( tries != 0 && guess < mystery) {
cout << guess << " is too low.\n" << endl;
cout << "You have " << tries << " tries: ";
}
}
if (guess == mystery) { //if guess == mystery by time loop ends you win
cout << "Got it! You Win!\n" << endl;
}
else { //if not, you lose
cout << "You Lose! The number was: " << mystery << ".\n" <<endl;
}
cout << "-------------------\n";
cout << "Play Again?(y/n): "; //ask user to play again
quit = play_again();
cout << "-------------------\n";
if (quit == false)
cout << endl;
} while (quit == false);
cout << "----------------------------------" << endl;
return 0;
}
I'm not sure how to fix this.
this line:
cin >> yn;
only reads the 'y' but not the end of line. As a result, the next execution of this instruction
getline (cin, guess);
initializes guess to an empty string.
On line 19, import the code "cin.ignore();" without quotations.
So your code reads as
`int check_guess(int tries) { //function for limiting the input of guess
string guess = "";
int result = 0;
do {
getline (cin, guess);
istringstream convert(guess);
if ( !(convert >> result) || (result < 1 || result > 100) ) {
result = 0;
cin.ignore();
cout << "Invalid Input.\n" << endl;
cout << "You have " << tries << " tries: ";
}
} while (result == 0);
return result;
}
`
and so on. This stops input into the console briefly. You're code is reading the 'y' to try again as the input for the number when you restart as well. Putting in the little line cin.ignore(), stops it from inputting y twice.
Change play_again() to:
bool play_again() { //function for limiting the input of mode
bool quit;
string yn;
do {
getline (cin, yn);
if ( yn == "y" || yn == "yes" ) {
quit = false;
}
else if ( yn == "n" || yn == "no" ) {
quit = true;
}
else {
yn = "invalid";
cout << "Invalid input.\n\nEnter 'y' or 'n': ";
}
} while ( yn == "invalid" );
return quit;
}
I made a little game where the program jumbles up a word and asks for player input. However, one of the If statements are giving me an error and stopping me from compiling the program.
string isready;
cin >> isready;
if (isready == 'y' || 'Y')
Above I set up a string to be called isready, than asked the user for input. As seen above,
I wanted the if statement to activate if either y or capital y was typed in and received.
However, it just gives me the error:
invalid operands to binary expression ('string'
(aka 'basic_string, allocator >') and 'int')
Perhaps I'm missing a #include file?
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <unistd.h>
using namespace std;
int main()
{
enum fields {WORD, HINT, NUM_FIELDS};
const int NUM_WORDS = 5;
const string WORDS[NUM_WORDS][NUM_FIELDS] = //5x2 array
{
{"wall", "Do you feel you're banging your head against something?"},
{"glasses", "These might help you see the answer."},
{"labored", "Going slowly, is it"},
{"persistent", "Keep at it."},
{"jumble", "It's what the game is all about."}
};
srand(static_cast<unsigned int>(time(0)));
int choice = rand() % NUM_WORDS;
//Choice value in array, than area in array where word and hint are
string theWord = WORDS[choice][WORD]; //word to guess
string theHint = WORDS[choice][HINT]; //hint for word
string jumble = theWord; //jumbled version of word
int length = jumble.size();
//Index1 and index2 are random locations in the string theWord
//last two lines swaps areas, ending the for function with a different
//jumble variable every time.
for (int i = 0; i < length; ++i)
{
int index1 = rand() % length;
int index2 = rand() % length;
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
cout << "\t\tWelcome to Word Jumble!\n\n";
cout << "Unscramble the letters to make a word.\n";
cout << "\n\n\nReady? (y/n)";
//I'm asking here if the player is ready
string isready;
cin >> isready;
if (isready == 'y' || 'Y')
{
cout << "Ok this is how the scoring works\n";
cout << "The length of the word you will guess is times by 5000.\n";
cout << "If you ask for a hint, your score will go down by half.\n";
cout << "If you get the wrong answer, your score will go down by 1000.";
cout << "\nOk, lets start!\n\n\n";
int counter = 3;
for(int i = 0; i < 3; ++i)
{
cout << counter << "..." << endl;
counter--;
}
sleep(1);
}
else
{
cout << "check";
}
cout << "Enter 'quit' to quit the game.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "The jumble is: " << jumble;
//Score system
unsigned long int score;
int amount_of_guesses, amount_of_wrong = 0;
string guess;
cout << "\n\nYour guess: ";
cin >> guess;
while ((guess != theWord) && (guess != "quit"))
{
if (guess == "hint")
{
cout << theHint;
amount_of_guesses++;
}
else
{
cout << "Sorry, that's not it.";
amount_of_wrong++;
}
cout << "\n\nYour guess: ";
cin >> guess;
}
score = theWord.length() * 1000 -(amount_of_wrong * 1000)
/ 2 * amount_of_guesses;
if (guess == theWord)
{
cout << "\nThat's it! You guessed it!\n";
}
cout << "Your score is: " << score;
cout << "\nThanks for playing.\n";
return 0;
}
here
(isready == 'y' || 'Y')
you are trying to use operator== on std::string and char, because 'y' is char. Apart from this conditions should be in parenthesis because || has lower precedence than ==
Correct version is:
( (isready == "y") || ( isready == "Y")) // use bool operator==
(const string& lhs,
const string& rhs);
Operator || takes logical expressions on both sides:
if (isready == "y" || isready == "Y")
Note the double quotes above, because isready is a std::string. You could also change isready to char, and use character constants (i.e. 'y' and 'Y' in single quotes).
Your current expression is syntactically valid, but it will be evaluated as unconditional true, because it is interpreted as follows:
if (isready == 'y' || 'Y' != 0)
// ^^^^^^^^
// != 0 part is implicit;
// `Y` != 0 is always true, so the entire OR is also always true
Change this statement
if (isready == 'y' || 'Y')
to
if ( isready == "y" || isready == "Y")
Take into account that there are double quotes.
The problem is that there is no such operator == that can compare an object of type std::string with an object of type char. There is no such a constructor in class std::string that could convert implicitly an object of type char to an object of type std::string. However class std::string has a constructor that can convert a string literal to an object of type std:string. So the right operand that is "y" or "y" is implicitly converted to a temporary object of type std::string. As the result in the condition above two objects of type std::string are compared.
Also the condition you wrote initially is invalid even if you would use string literals instead of character literals. If for example isready == "y" was equal to false then you will get
false || "y"
In this expression string literal "y" is converted to a pointer to its first character. As this pointer is not equal to NULL then the whole expression will be true independing of the value in isready
(isready == 'y' || 'Y')
You should check for each character seperately.
((isready == "y" || (isready == "Y"))
if (isready == 'y' || 'Y')
should be
if (isready == "y" || isready == "Y")