My If statement isn't accepting '==' - c++

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")

Related

How to fix: else statement not being called c++ [duplicate]

I am not sure what I'm doing wrong here, every time I run it, it goes through the if part even when it's not true? So the 'else' never runs.
#include <iostream>
using namespace std;
string choice;
float numb;
float convert(float numb,string choice)
{
float newNo;
if (choice == "F" or "f"){
newNo = numb * 0.2 * 9 + 32;
}else{
newNo = (numb - 32) / 1.8;
}
return newNo;
}
int main()
{
cout << "welcome to Temperature converter v0.1" << endl;
cout << endl;
cout << "Which conversion would you like to use?" << endl;
cout << "type C to convert to Celsius and F to convert to Fahrenheit - ";
cin >> choice;
cout << "what number would you like to convert? - ";
cin >> numb;
cout << convert(numb,choice);
return 0;
}
The problem is your if Statement:
if (choice == "F" or "f"){
basically, what you say here is:
If choise is "F" or if "f". You need to understand: True is everything besides zero (0). "f" is NOT zero, so it is true. You could also wirte (or = ||):
if (coice == "F" || true)
which is the same like:
if (true)
So in order for your code to work, you need:
if (choice == "f" || choice == "F")
That would do what you expect.
There is a problem in the syntax of 'if' statement. Following is the corrected code, where '||' stands for 'or':
if ((choice == "F") || (choice=="f")){
newNo = numb * 0.2 * 9 + 32;
}else{
newNo = (numb - 32) / 1.8;
}
Change this if statement
if (choice == "F" or "f"){
to the following
if (choice == "F" or choice == "f"){
Otherwise the right operand of the operator or
"f"
is always equal to true because it is converted to the address of the first character of the string literal that evidently is not equal to 0.
That is your original condition in the if statement looks like
if (choice == "F" or "f" != nullptr){
and indeed "f" != nullptr

I want to replace all the vowels with z in string

This code is replacing all the characters. Not just vowels. What am I doing wrong?
using namespace std;
bool isVowel(char);
int main() {
string fName = "";
string lName = "";
cout << "Enter first name: " << endl;
cin >> fName;
cout << "Enter last name: " << endl;
cin >> lName;
string name = fName + " " + lName;
cout << name << endl;
for(int i = 0; i < name.length(); i++) {
if(isVowel(name.at(i))) {
name[i] = 'z';
}
}
cout << name << endl;
}
bool isVowel(char c) {
if(c == 'a' || 'e' || 'i' || 'o' || 'u' || 'A' || 'O' || 'E' || 'I' || 'U') {
return true;
}
else {
return false;
}
}
I did some research online and I think my problem lies in that I am passing the character as a reference? I didn't understand how that could be...
The isVowel() function checks if the char is a vowel I think that's where the problem lies, since the program is replacing all the characters I'm assuming that function is not working.
you need to put your if statement as (c == 'a' || c == 'e' || c == 'i'..., the way it is written currently it casts all of the characters on their own as boolean expressions.

Fixing uninitialized local variable error

I am working on a project right now and when I try to run what I have below it gives me an error that says "uninitialized local variable 'userOption' used" on line 22, while (isValidOption(userOption) == true) {.
How do I fix that error? Thank you.
#include<iostream>
#include <string>
using namespace std;
char toupper(char ch) {
if (ch >= 'A'&&ch <= 'Z')
return(ch);
else
return(ch - 32);
}
bool isValidOption(char ch) {
if (ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X')
return(true);
else
return(false);
}
char getMainOption() {
string UserInput;
char userOption;
while (isValidOption(userOption) == true) {
cout << "Choose One of the following options\n";
cout << "I--List Our Inventory\n";
cout << "O--Make an Order\n";
cout << "L--List all Orders made\n";
cout << "X--Exit\n";
cout << "Enter an option: ";
getline(cin, UserInput);
userOption = toupper(UserInput[0]);
if (!isValidOption(userOption)) {
cout << "Invalid String\n";
cout << "Enter an option: ";
getline(cin, UserInput);
userOption = toupper(UserInput[0]);
}
if (userOption == 'I')
cout << "Listing Our Inventory\n";
else if (userOption == 'O')
cout << "Make an order\n";
else if (userOption == 'L')
cout << "Listing all orders\n";
}
return userOption;
}
int main() {
char choice;
choice = getMainOption();
system("pause");
return 0;
}
What the error is saying that you're trying to read from userOption before you've ever written to it. If a variable is uninitialized, its memory contents will be full of junk left behind by other functions and it can easily cause bugs. In your case, you'll want to read input from the user into userOption before you do any logic on it. This can be done with a do-while loop:
char userOption; // not yet initialized
do {
...
cin >> userOption; // userOption gets initialized here on first loop run
} while (isValidOption(userOption)); // no need for == true, that's a tautology :-)
// NOTE: perhaps you want to loop while the input is INvalid, as in
// while (!isValidOption(userOption)); ?
A couply code-review comments I would additionally give are:
std::toupper already exists in <cctype>. Docs are here
return is not a function call and it's better to write return ch; than return(ch);
if (ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X'){ return true; } else { return false; } is completely equivalent to the shorter return ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X';
Also take a look at system(“pause”); - Why is it wrong?
Happy coding! Let me know if questions remain

What is the purpose of "input.length();"?

I am taking a college level C++ course, and quite frankly nothing is really ever explained. I was given code to write, and my program works as it should. I would just like to know the purpose of certain lines.
Such as:
int i = 0;
I know I am declaring an int variable that = 0. Here my question is why the letter i? Could that be any variable name I choose?
int length = input.length();
I know I am declaring an int variable named length... but what purpose does it serve in my code?
i++
I think this ends my loop?
I have added my code for perusal. Any assistance would be greatly appreciated!
// Program takes user entered letter and matches it with the corresponding ICAO word.
//Program has been modified to use void and string methods
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
//Function Heading
void convert(string);
//Main Function
int main()
{
string input;
cout << " Enter a letter or word: "; // Ask the user to enter a letter or word.
cin >> input; //get input
cout << "Phonetic Version : "; //Display "Phonetic Version"
convert (input);
cout << endl;
system("pause");
}//End Main
//Function Definition
void convert(string input)
{
int i = 0; //input variable
char letters; //character variable
int length = input.length();
while (i < length) //While loop initialized
{
letters = input.at(i);
if (letters == 'a' || letters == 'A')
cout << "Alpha ";
else if (letters == 'b' || letters == 'B')
cout << "Bravo ";
else if (letters == 'c' || letters == 'C')
cout << "Charlie ";
else if (letters == 'd' || letters == 'D')
cout << "Delta ";
else if (letters == 'e' || letters == 'E')
cout << "Echo ";
else if (letters == 'f' || letters == 'F')
cout << "Foxtrot ";
else if (letters == 'g' || letters == 'G')
cout << "Golf ";
else if (letters == 'h' || letters == 'H')
cout << "Hotel ";
else if (letters == 'i' || letters == 'I')
cout << "India ";
else if (letters == 'j' || letters == 'J')
cout << "Juliet ";
else if (letters == 'k' || letters == 'K')
cout << "Kilo ";
else if (letters == 'l' || letters == 'L')
cout << "Lima ";
else if (letters == 'm' || letters == 'M')
cout << "Mike ";
else if (letters == 'n' || letters == 'N')
cout << "November ";
else if (letters == 'o' || letters == 'O')
cout << "Oscar ";
else if (letters == 'p' || letters == 'P')
cout << "Papa ";
else if (letters == 'q' || letters == 'Q')
cout << "Quebec ";
else if (letters == 'r' || letters == 'R')
cout << "Romeo ";
else if (letters == 's' || letters == 'S')
cout << "Sierra ";
else if (letters == 't' || letters == 'T')
cout << "Tango ";
else if (letters == 'u' || letters == 'U')
cout << "Uniform ";
else if (letters == 'v' || letters == 'V')
cout << "Victor ";
else if (letters == 'w' || letters == 'W')
cout << "Whiskey ";
else if (letters == 'x' || letters == 'X')
cout << "X-ray ";
else if (letters == 'y' || letters == 'Y')
cout << "Yankee ";
else if (letters == 'z' || letters == 'Z')
cout << "Zulu ";
i++;
}
}
int length = input.length();
I know I am declaring an int variable named length... but what purpose
does it serve in my code?
None.
It would serve some purpose if input's length would change later on and you'd need to remember the old length for some reason.
Since this is not the case here, your professor may think that this is some kind of "optimisation" on the grounds that repeatedly calling length() may be too slow. But this is nonsense; your computer is too fast for such micro-optimisations to have an observable effect, especially with modern compilers being much better at optimising programs than the programmers themselves.
Just remove the length variable to make the code shorter.
Here
string input;
std::string has a method called length() which returns the length of the string, in terms of bytes. Hence you are using like
int length = input.length(); /* use variable name as other than predefined method to avoid confusion */
| |
this is just this is a method of string
a int variable
int i = 0;
I know I am declaring an int variable that = 0. Here my question is why the letter i? Could that be any variable name I choose?
Yes. Variable names are arbitrary, name them however you want (within the restrictions of the language syntax, of course). Just make sure you use names that are meaningful within the context in which they are being used. Readability matters when maintaining code over time.
int length = input.length();
I know I am declaring an int variable named length... but what purpose does it serve in my code?
To make a local cached copy of the character count of the input string so your loop does not have to keep calling the string's length() method over and over. Using a few bytes of local stack space can save time and overhead of retrieving the string's length, which does not change while the loop runs.
i++
I think this ends my loop?
It increments the value of the i variable, nothing more. The loop ends when the while statement evaluates as false (when i catches up to length).

Two conditions for while loop. What's my error?

I have a questoin. Everything here seems to work fine, besides the following line:
} while (OneMoreTime != 'y' || OneMoreTime != 'n');
Full Code;
#include <iostream>
using namespace std;
int main()
{
int ARRAY_LENGTH = 5;
int MyArray[ARRAY_LENGTH] = {1, 2, 3, 4, 5};
cout << "Values in the array: " << ARRAY_LENGTH << endl;
for (char OneMoreTime = '\0'; OneMoreTime = 'n'; )
{
int WhichNumber = ARRAY_LENGTH;
do
{
cout << "What numbers from the array do you want to see, counting backwards? ";
cin >> WhichNumber;
} while ((WhichNumber > ARRAY_LENGTH) || (WhichNumber <= 0));
//calculating the correct position in the array (from start)
int Number2Print = ARRAY_LENGTH - WhichNumber;
//printing
cout << "The number is: " << MyArray[Number2Print] << endl;
//continue?
do
{
cout << "One more time? (y/n) ";
cin >> OneMoreTime;
} while (OneMoreTime != 'y' || OneMoreTime != 'n');
}
return 0;
}
What I get is it constantly asks "One more time? (y/n)" after successfully printing the first time. If I just use one condition it will work (but that wouldn't be enough).
That condition will always be true as OneMoreTime cannot be both equal to n and y. What you probably mean is to use && (and)
while (OneMoreTime != 'y' && OneMoreTime != 'n');
this statment
while (OneMoreTime != 'y' || OneMoreTime != 'n');
is a false statment, what you will get is no matter what you put in is gonna return true and
continue the loop.
A || B, if you put 'y' ,B is true, if you put 'n', A is true, so the 'or' operation will return true if either one of the condition is true.
if you using
while (OneMoreTime != 'y' && OneMoreTime != 'n');
it will still put next value in the array if you input 'n'