Very new to C++, only been working with it for a few days. I'm trying to write a simple console calculator that requests the user input a Y or N to confirm that the result printed was actually correct.
I've called to a function that requests the user input a char for Y/N, which then returns that as a bool value as either true or false depending on what was inputted. It then returns to main with that bool, which is then passed onto another function that prints text depending upon whether true or false was passed. However whenever I run the program, it always prints both statements for true and false. I'm sure I've broken some kind of rule when using bools or there's some sort of small error but I can't seem to find it. Any help would be greatly appreciated.
bool getConfirmation()
{
std::cout << "Is this result correct? Y/N: ";
char confirm;
std::cin >> confirm;
if (confirm == 'Y', 'y') return true;
if (confirm == 'N', 'n') return false;
else return false;
}
void confirmResult(bool confirm)
{
if (confirm == true)
std::cout << "Result is correct.";
if (confirm == false)
std::cout << "Sorry, please try again.";
else
std::cout << "Sorry, please try again.";
}
int main()
{
std::cout << "Please input the first integer: ";
int x{ getInteger() };
std::cout << "Please input the desired operation: ";
char op{ getOperation() };
std::cout << "Please input the second integer: ";
int y{ getInteger() };
int result{ calculateResult(x, op, y) };
printResult(result);
bool confirm{ getConfirmation() };
confirmResult(confirm);
return 0;
}
confirm == 'Y', 'y' doesn't do what you think it does - this is an expression involving the built-in comma operator, which always evaluates to 'y'. The correct code is:
confirm == 'Y' || confirm == 'y'
You will always see both
std::cout << "Result is correct.";
std::cout << "Sorry, please try again.";
being executed because your boolean logic is incorrect.
if (confirm == true)
A
if (confirm == false)
B
else
C
If confirm == true, then both A and C will be executed, as the second if statement is not introduced by an else. Your logic should just be:
if (confirm == true)
std::cout << "Result is correct.";
else
std::cout << "Sorry, please try again.";
Related
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double addition;
double subtraction;
double top, bottom;
double multiplication, multiplication2;
char variable;
double total = 0.0;
cout << "Type in:\n'A' For Addition\n"
<< "'S' For subtraction\n" << "'D' For division\n"
<< "'M' For multiplication\n";
cin >> variable;
switch (variable)
{
case 'A':
{
cout << "Enter 0 for input\n";
cin >> addition;
while(addition != 'Q' || addition != 'q')
{
cout << "Enter numbers for adding\nThen type in"
<< "Q or q to quit\n";
cin >> addition;
total += addition;
}
cout << "Your total is " << total << endl;
}
It loops infinitely starting out at the first cout statement in the while loop. I will type in numbers, then as soon as I type in q or Q and hit enter it will immediately loop infinitely. Thanks!
Your condition for the while loop uses a logical OR.
Let's say you try to quit the loop and enter the input 'Q'. The first part of the condition will be FALSE, but the second part of the condition will be TRUE. Since it is a logical OR, then the whole condition will be TRUE and the loop will execute. The converse is also true if you input 'q'.
So no matter what you enter, your loop will run.
There are two main problems in your program.
First, condition addition != 'Q' || addition != 'q' is always true, because for any value of addition, either addition != 'Q' or addition != 'q' is true (i.e. addition can never be both Q and q at the same time). You probably meant addition != 'Q' && addition != 'q'
Second, when you do cin >> addition with variable of type double, then you will either receive a valid number or - if somebody enters - 'Q', for example, "nothing" and an error flag is set. "Nothing" means that the value of addition remains unchanged.
To accomplish the "either a number or 'Q'"-thing, you need to read in a string and compare it to "Q" (or "q") and otherwise try to convert the string into a double.
The code fragment could look as follows:
int main() {
double sum = 0;
double toAdd;
std::string input;
bool end = false;
while (!end) {
cout << "enter a value to add (type Q or q to quit)" << endl;
cin >> input;
if (input == "Q" || input == "q") {
end = true;
}
else {
try {
toAdd = stod(input);
sum += toAdd;
} catch (out_of_range &e) {
cout << "input " << input << " is out of range." << endl;
} catch (invalid_argument &i) {
cout << "input " << input << " is not a valid number." << endl;
}
}
}
cout << "sum: " << sum << endl;
}
#include <iostream>
using namespace std;
int main(){
cout << endl;
cout << "Welcome to the wonderful world of a spy" << endl;
cout << "Today we are to decode some information that has been provided." <<endl;
string response;
cout << "Are you ready?" << endl;
cin >> response;
if (response == "yes", "y", "Yes", "Y"){
cout << "Alright, let's go!!!" << endl;
}
else {
cout << "Well, too bad. We are going to do it anyways." << endl;
}
}
Exact Code Here is my code thus far. I can't get it to not say "Alright, let's go!!! What am I doing wrong?
The line if (response == "yes", "y", "Yes", "Y") doesn't do what you think it does. The comma operator evaluates each of its operands, discards the result on the left and takes the result on the right as the result of the expression. So what you wrote is equivalent to if ("Y"). You need to use the logical OR operator to combine your different cases. Like this if (response == "yes" || response == "y" || response == "Yes" || response == "Y").
your if statement conditions are wrong.
if(response == "yes" || response == "y" || response == "Yes" || response == "Y")
{
//then do whatever...
}else{
//do it anyway...
}
This question already has answers here:
How to compare multiple strings inside an if statement?
(6 answers)
Closed 5 years ago.
My program keeps looping and never get's to "return 0;". Is it the compiler that's bad or the code?
#include<iostream>
using namespace std;
int main() {
string nameInput = "";
string Input = "Yes";
cout << "Welcome to the purple casino!" << endl << "What's your name?" << endl;
while(Input =="Yes" || "yes"){
getline(cin, nameInput);
cout << nameInput << ", what a nice name!" << endl << "Do you want to change it?" << endl;
getline(cin, Input);
if(Input =="Yes" || "yes"){
cout << "To what?" << endl;
}
}
cout << "Let's begin!";
return 0;
}
The expression Input == "Yes" || "yes" is evaluated, due to operator precedence, as
(Input == "Yes") || "yes"
which is always true. This is because the const char[4] literal "yes" decays to a const char* type, with a non-zero pointer value.
You need Input == "Yes" || Input == "yes"
My program keeps looping and never get's to “return 0;”. Is it the compiler that's bad or the code?
The code, as (almost) always.
Input =="Yes" || "yes" will always evaluate to true, no matter what Input's value really is, since it boils down to saying:
true if: Input equal to "Yes" OR "yes".
false if otherwise.
A string literal evaluates to true, thus the second operand of the logical or will be true, causing the whole logical expression to evaluates to true, always!
As a result your while loop's condition is always true, resulting in an infinite loop!
So change this:
while(Input =="Yes" || "yes")
to this:
while(Input =="Yes" || Input == "yes")
PS: Change the condition of the if statement similarly, since it's the same exact condition.
Your while statement's condition is wrong:
while (Input == "Yes" || "yes")
as "yes" operand always evaluates to true causing the entire condition to be true. Try this instead:
while (Input == "Yes" || Input == "yes")
There is a silly mistake in your code. Please see the below edited code -
#include<iostream>
using namespace std;
int main(){
string nameInput = "";
string Input = "Yes";
cout << "Welcome to the purple casino!" << endl << "What's your name?" <<
endl;
while(Input =="Yes" || Input == "yes"){ // Error was here
getline(cin, nameInput);
cout << nameInput << ", what a nice name!" << endl << "Do you want to
change it?" << endl;
getline(cin, Input);
if(Input =="Yes" || "yes"){
cout << "To what?" << endl;
}
}
<< "Let's begin!";
return 0;
}
Try modifying while(Input =="Yes" || "yes"){ to while(Input =="Yes" || Input == "yes"){
I think the problem will be solved.
Hi before return try :
cout << "Let's begin!";
And change in While and if your condition to:
(Input =="Yes" || Input=="yes")
In a more general way, if you have a loop from which your program never returns, it means that the condition you passed always evaluates to true.
In your case indeed, an as others already answers, the condition
while (Input == "Yes" || "yes")
always evaluate to true because of the second part.
What you really want is to check if Input is "Yes" OR Input is "yes", which in C++ should be written :
while (Input == "Yes" || Input == "yes").
Hope, this more general answer will help.
I started building a very simple version of a calculator in C++. The idea is to perform basic operations with only two numbers and then loop back so the user can make a new calculation.
The program looks like this:
#include<iostream>
#include<string>
#include"mathOperations.h"
using namespace std;
int main()
{
int x, y;
string operation;
string repeat = "y";
while (repeat == "y" or "Y")
{
cout << "Welcome! This is a raw version of a calculator - only use two numbers." << endl;
cin >> x >> operation >> y;
if (operation == "+")
{
cout << "Result: " << add(x, y) << endl;
}
else if (operation == "-")
{
cout << "Result: " << subtract(x, y) << endl;
}
else if (operation == "*")
{
cout << "Result: " << multiply(x, y) << endl;
}
else if (operation == "/")
{
cout << "Result: " << divide(x, y) << endl;
}
else
{
cout << "This is not a valid sign. Please choose another one!" << endl;
}
cout << "Wanna go again? Type 'y' or 'n'." << endl;
cin >> repeat;
if (repeat == "n" or "N")
{
cout << "Alright, have a nice day!" << endl;
break;
}
}
}
int add(int x, int y)
{
return x + y;
}
int subtract(int x, int y)
{
return x - y;
}
int multiply(int x, int y)
{
return x * y;
}
int divide(int x, int y)
{
return x / y;
}
NOTE: There is a 'mathOperations.h' file in which I have made forward declarations of all functions used.
The problem is that whenever I type in 'y' to make it loop, it simply outputs the following 'if' statement and breaks out of the loop and the program finishes. I couldn't quite figure out why this is happening, since the 'if' statement is only supposed to run if I type in 'n'.
repeat == "n" or "N"
evaluates to
(repeat == "n") || "N"
see the C++ operator precedence.
The first repeat == "n" evaluates to true or false depending on your input, but the second clause of the OR, i.e. "N", always evaluates to true because it is a string literal that decays to a non-zero const char* pointer, and in C or C++ everything non-zero is implicitly converted to true. So your OR clause is always true, which implies that the if block will always be executed.
As mentioned in the comments, you need to do
if(repeat == "n" || repeat == "N") {...}
Similarly with the first while condition.
Nice code! I try using "||" in place of your "or" in your if statements. Might want to refresh your knowledge with C++ short-circuiting of booleans.
int OnLoad() {
cout << "Hi whats your name? ";
cin >> name;
system("cls");
cout << "Hi " << name << "." << " Are you here to Take Over the city from zombies?"<< endl;
cin >> userInput;
if (userInput == "yes" || "Yes") {
cout << "Yes" << endl;
}
else if (userInput == "no" || "No") {
cout << "No" << endl;
}
else {
cout << "I don't understand." << endl;
}
return 0;
}
int main() {
OnLoad();
system("pause");
return 0;
}
This code only returns Yes back, after the console window pops up and ask are you here to take over the city from zombies even after i type no it returns yes!
if (userInput == "yes" || "Yes")
actually means
if ((userInput == "yes") || ("Yes"))
It's logical OR between two expressions: userInput == "yes" and "Yes". The first one is correct and evaluates to bool directly. The second one is just a char* that will be converted to bool implicitly. Since it's a compile time string it cannot be nullptr, which means it will always evaluate to true. And that, in turn, means the whole condition is always true (that's how logical OR works).
The correct code is
if (userInput == "yes" || userInput == "Yes")
P. S. This is why I always recommend compiling with the highest warning level possible (/W4 for MSVC, -Wall -pedantic-errors for GCC and clang). Most compilers will generate a warning in this case.
that's not how the || operator works, if you just put "Yes" as a condition it will always evaluate to true
if (userInput == "yes" || userInput == "Yes") {
cout << "Yes" << endl;
}
the reason why is because of precedence
userInput == "yes"
and
userInput == "Yes"
get evaluated before || ( logical OR)