Can't find the bug/probleem in my program [duplicate] - c++

This question already has answers here:
Why is this only returning "yes"
(2 answers)
Closed 6 years ago.
I'm making my first project c++. It's a simple temperature converter.
I made a test section [code 1] with if statements. the if statement would compare the user input. for example if you user typed c and then k(Celsius-Kelvin). it should run the function[code 2] CtoK(); but i doesn't it runs all function why does it do this?
It try to use return but i didn't(it also didn't gave a error so i kept it)
If you guys see something else pls say it Code on pastebin
Also thinks to keep it mind:
Just stated to learn C++
Not native English so if there are spelling and grammar mistakes please say it so i can learn form it
[code 1]
void whatToWhat(char firstDegrees, char secondDegrees) {
if (firstDegrees == 'C' || 'c') {// tests if the user want form c to f
if (secondDegrees == 'F' || 'f') {
CtoF();
}
}if (firstDegrees == 'C' || 'c') {// tests if the user want form c to k
if (secondDegrees == 'K' || 'k') {
CtoK();
}
}if (firstDegrees == 'F' || 'f') {// tests if the user want form f to c
if (secondDegrees == 'C' || 'c') {
FtoC();
}
}if (firstDegrees == 'F' || 'f') {// tests if the user want form f to k
if (secondDegrees == 'K' || 'k') {
FtoK();
}
}if (firstDegrees == 'K' || 'k') {// tests if the user want form k to f
if (secondDegrees == 'F' || 'f') {
KtoF();
}
}if (firstDegrees == 'K' || 'k') {// tests if the user want form k to c
if (secondDegrees == 'C' || 'c') {
KtoC();
}
}
}
[code 2]
void CtoF() {// c to f furmula
double input;
cout << "Enter a number[Celsius-Fahrenheit]" << endl;
cin >> input;
cout << "it's " << input * 1.8 + 32 << " Fahrenheit " << endl;
return;
}
void CtoK() {// c to k furmula
double input;
cout << "Enter a number[Celsius-Kelvin]" << endl;
cin >> input;
cout << "it's " << input + 273.15 << " Kelvin " << endl;
return;
}
void FtoC() {//f to c furmula
double input;
cout << "Enter a number[Fahrenheit-Celsius]" << endl;
cin >> input;
cout << "it's " << input / 1.8 - 32 << " Celsius " << endl;
}
void FtoK() {//f to k furmula
double input;
cout << "Enter a number[Fahrenheit-Kelvin]" << endl;
cin >> input;
cout << "it's " << input / 1.8 - 32 + 273.15 << " Kelvin " << endl;
return;
}
void KtoF() {// k to f furmula
double input;
cout << "Enter a number[Kelvin-Fahrenheit]" << endl;
cin >> input;
cout << "it's " << (input - 273.15) * 1.8 + 32 << " Fahrenheit " << endl;
}
void KtoC() {// k to c furmula
double input;
cout << "Enter a number[Kelvin-Celsius]" << endl;
cin >> input;
cout << "it's " <<273.15 - input << " Celsius " << endl;
return;
}

if(firstDegrees == 'K' || 'k') will always evaluate to true since k as it is is Not Null, means Valid, means True.
You need to write all your expressions in a similar way to this: (firstDegrees == 'K' || firstDegrees == 'k')
Also, you would want to add elses after each if, for better and clearer logic control.

Related

How to make cin accept a single digit only c++

So we were challenged by a teacher to make this simple game into a c++ program.
English is not my primary language but I'll try to explain. I'm a beginner so these will not be efficient, but I'm still proud of what I did so far.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int secret[3], i = 0, x, y, z, a, b, c, guess = 1, tries = 9;
bool correct = false;
srand(time(0));
do
{
secret[i] = rand() % 10;
i++;
} while (i <= 2);
x = secret[0];
y = secret[1];
z = secret[2];
//cout << x << y << z << endl; <--- for debugging purposes
cout << "=================================================\n\n";
cout << " I HAVE THREE SINGLE DIGIT NUMBERS\n\n";
cout << " YOU HAVE TEN TRIES TO GUESS ALL THREE DIGITS\n\n";
cout << "=================================================\n\n";
do
{
cout << "\n\nGuess the first digit.\n";
while (!(cin >> a))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n";
}
cout << "\n\nGuess the second digit.\n";
cout << a;
while (!(cin >> b))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n" << a;
}
cout << "\n\nGuess the third digit.\n";
cout << a << b;
while (!(cin >> c))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n" << a << b;
}
cout << "\n\n====================================================\n\n";
if (tries == 0)
{
cout << "YOU RAN OUT OF GUESSES! \n";
cout << "The secret number is " << x << y << z << "!\n";
cout << "PLEASE RESTART THE PROGRAM TO TRY AGAIN!\n";
correct = true;
}
else if ((a == x) && (b == y) && (c == z))
{
cout << "YOU GUESSED THE SECRET NUMBER IN " << guess << " TRY / TRIES!\n";
cout << "CONGRATULATIONS!\n\n";
correct = true;
}
else if ((a == x) && (b == y) && (c != z))
{
cout << "You guessed TWO of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a == x) && (b != y) && (c != z))
{
cout << "You guessed ONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a == x) && (b != y) && (c == z))
{
cout << "You guessed TWO of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a != x) && (b == y) && (c == z))
{
cout << "You guessed TWO of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a != x) && (b == y) && (c != z))
{
cout << "You guessed ONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a != x) && (b != y) && (c == z))
{
cout << "You guessed ONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else
{
cout << "You guessed NONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
cout << "\n====================================================\n\n";
guess++;
tries--;
} while (correct == false);
}
I have a little problem though, in this part of the program,
cout << "\n\nGuess the first digit.\n";
while (!(cin >> a))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n";
}
I could enter anything invalid and it will properly identify it as an invalid input. But if I enter 2 digits (22 for example), the program still enters 22 and it just accepts it.
I don't know exactly how that part of my program works, I just copy-pasted it. Is it possible to modify it, or my program to only accept a single digit, 0-9, and identify the input as invalid when two numbers are entered?
I know it's just a minor inconvenience and doesn't really break the program, but if I can make it better then it would be great. I just want it to be perfect, if possible.
I'm guessing if there's something like _getche for integers then it would be better?
Thanks in advance.
while (!(cin >> a)) means keep looping while not able to convert the input to an integer value in a - you can add extra conditions:
while (!(cin >> a) || a < 0 || a > 9)
In those latter cases, there's no need to .clear() and .ignore(...) but it won't do any harm.
In case it's new to you, || means logical-or, the equivalent logic to English such as: "a is less than 0 OR a is greater than 9".

c++ program runs incorrect else statement

When I run the program, I can't figure out why when I ask for the letter a, b, or c and a different letter is inputted other than those, why is it going to "invalid criteria" instead of "An invalid code has been entered. When I input a number out of the range it goes to "Invalid number has been entered" but not when I'm asking for the letter
#include <iostream>
#include <iomanip>
#include "Header.h"
using namespace std;
int main()
{
head();
int num_1, a, b, c;
char char_1;
float num_2;
num_2 = 28.82;
a = b = c = 0;
cout << "Please enter a number between 10 and 30." << endl;
cin >> num_1;
if (num_1 >= 10 && num_1 <= 30)
{
cout << "Enter the letter a, b, or c." << endl;
cin >> char_1;
if (char_1 == 'a'||'b'||'c')
{
if ((num_1 >= 10 && num_1 <= 20) && (char_1 == 'a'))
{
num_2 = num_2 + .5;
cout << fixed << setprecision(1) << num_2 << endl;
}
else if ((num_1 >= 19 && num_1 <= 30) && (char_1 == 'b'))
{
num_2 = num_2 + .10;
cout << fixed << setprecision(2) << num_2 << endl;
}
else if ((num_1 >= 19 && num_1 <= 30) && (char_1 == 'c'))
{
num_2 = num_2 + .100;
cout << fixed << setprecision(3) << num_2 << endl;
}
else
{
cout << "Invalid criteria" << endl;
}
}
else
cout << "An invalid code has been entered."
}
else
cout << "An invalid number has been entered." << endl;
system("pause");
return 0;
}
The expression:
char_1 == 'a' || 'b' || 'c'
is equivalent to:
char_1 == ('a' || 'b' || 'c')
and therefore first evaluates the logical or of all those letters treated as booleans (all true hence the result is true), then compares that with your variable.
What you need is:
(char_1 == 'a') || (char_1 =='b') || (char_1 =='c')
This checks the character against each of the possibilities and then works out whether any of them were true.

using multiple and or statements in if condition

#include <iostream>
using namespace std;
main()
{
char a[2];
cout << " \"Welcome to Virtual University\" " << endl;
cout << " Program to predict user programming level" << endl;
cout << " Please answer in either T=True or F=False" << endl;
cout << "Q:1 Switch is a loop?" << endl;
cout << "A: ";
cin >> a[0];
cout << "Q:2 Pointer stores memory address?" << endl;
cout << "A: ";
cin >> a[1];
cout << "Q:3 Semicolon after for loop is an error? " << endl;
cout << "A: ";
cin >> a[2];
if((a[0] == 'f') || (a[0] == 'F') && (a[1] == 't') || (a[1] == 'T') && (a[2]
== 'f') || (a[2] == 'F'))
{
cout << "Your programming level is advanced" << endl;
}
else if((a[0] == 'f') || (a[0] == 'F') && (a[1] == 't' ) || (a[1] == 'T')
&& (a[2]== 't') || (a[2] == 'T'))
{
cout << "Your programming level is intermediate" << endl;
}
else if((a[0] != 'f') || (a[0] != 't') && (a[1] != 't' ) || (a[1] != 'f') &&
(a[2] != 't') || (a[2] != 'f'))
{
cout << "please enter t or f only" << endl;
}
else
{
cout << "Your programing level is begginner" << endl;
}
return 0;
}
its not giving any errors in compiler but when i run this`` program it always prints the wrong statement. can you guyz please help me.
and when i remove the || conditions with capital F and T. its working fine.
can any one help putting those capital letters as well because its a requirement in my assignment. thanks in advance.

Nothing happening when I call my function?

I'm trying to make a function for a rock, paper, scissors game with two char parameters where the first one represents the user's choice of rock, paper, or scissors. The second parameter represents the result of the game, either win, loss, or tie. When I tried to call the function, however, nothing is happening. I'm lost on what exactly I need to do next. All help is greatly appreciated!
#include <iostream>
#include <cstdlib>
using namespace std;
double playRPS (char a, char b);
int main() {
char letter;
char result = 0;
cout << "Welcome to COP3014 ROCK PAPER SCISSORS!\n\n";
cout << "Please select: " << endl
<< "Rock(r), Paper(p), or Scissors(s)? " << endl
<< "Or enter q to quit --> ";
cin >> letter;
if (letter == 'r' || letter == 'R' || letter == 'p' || letter == 'P' || letter == 's' || letter == 'S') {
playRPS(letter, result);
}
else {
cout << "Please enter r, p, or s" << endl;
}
return 0;
}
double playRPS (char x, char y) {
int choice1 = 0, choice2 = 0, choice3 = 0;
int user2 = rand() % 3 + 1;
if (( x == 'r' || x == 'R') && (user2 == '2')) {
cout << "The computer chose... PAPER!";
cout << "You chose ROCK!";
cout << "You LOSE!";
y = choice2;
return choice2;
}
else if ((x == 'r' || x == 'R') && (user2 == '1')) {
cout << "The computer chose... ROCK!";
cout << "You chose ROCK!";
cout << "You TIED!";
y = choice3;
return choice3;
}
else if ((x == 'r' || x == 'R') && (user2 == '3')) {
cout << "The computer chose... SCISSORS!";
cout << "You chose ROCK!";
cout << "You WIN!";
y = choice1;
return choice1;
}
else if (( x == 'p' || x == 'P') && (user2 == '2')) {
cout << "The computer chose... PAPER!";
cout << "You chose PAPER!";
cout << "You TIED!";
y = choice3;
return choice3;
}
else if (( x == 'p' || x == 'P') && (user2 == '1')) {
cout << "The computer chose... ROCK!";
cout << "You chose PAPER!";
cout << "You WIN!";
y = choice1;
return choice1;
}
else if (( x == 'p' || x == 'P') && (user2 == '3')) {
cout << "The computer chose... SCISSORS!";
cout << "You chose PAPER!";
cout << "You LOSE!";
y = choice2;
return choice2;
}
else if (( x == 's' || x == 'S') && (user2 == '2')) {
cout << "The computer chose... PAPER!";
cout << "You chose SCISSORS!";
cout << "You WIN!";
y = choice1;
return choice1;
}
else if (( x == 's' || x == 'S') && (user2 == '1')) {
cout << "The computer chose... ROCK!";
cout << "You chose SCISSORS!";
cout << "You LOSE!";
y = choice2;
return choice2;
}
else if (( x == 's' || x == 'S') && (user2 == '3')) {
cout << "The computer chose... SCISSORS!";
cout << "You chose SCISSORS!";
cout << "You TIED!";
y = choice3;
return choice3;
}
else{
return main();
}
General remarks
using namespace std;
Avoid using namespace std.
return main();
You are not allowed to call main in your code. This will result in Undefined Behavior. Plus, what is your intention here?
rand()
rand() should be avoided. Here is an interesting video on why you should not use it, and instead use C++11 random.
y = choice2;
You are passing y by value, which means assigning it won't modify the y from the outside. You should pass y by reference when doing this (i.e. char& y in the declaration).
Why is the function not doing anything?
... Actually, it does!
user2 == '2'
Your comparisons are broken. '2' is actually not 2, but 50. The reason is that '2' is a character, so you actually are reading the associated character code.
This means all of your conditions are false in playRPS, so the only thing the function does it to call main() (in return main();).
What about shortening your code?
Your test cases are quite redundant and heavy. You could change it to drastically cut down your code size.
Let's print what the choice selected by the player...
if (x == 'r' || x == 'R')
cout << "You chose ROCK!" << endl;
else if (x == 'p' || x == 'P')
cout << "You chose PAPER!" << endl;
else if (x == 's' || x == 'S')
cout << "You chose SCISSORS!" << endl;
All good! Let's do the same with the computer's choice!
if (user2 == 1)
cout << "The computer chose... ROCK!" << endl;
else if (user2 == 2)
cout << "The computer chose... PAPER!" << endl;
else if (user2 == 3)
cout << "The computer chose... SCISSORS!" << endl;
Then you should compare what the player chose to what the computer chose, and tell who is the winner. Unfortunately, we can't compare x to user2 without doing many cases again...
What if we decided to have x's choice being saved the same way as user2? We also can use tolower to avoid checking for the caps variant of the letter.
int user1 = 0;
x = tolower(x); // we force x to lower case
if (x == 'r')
user1 = 1;
else if (x == 'p')
user1 = 2;
else if (x == 's')
user1 = 3;
Good! Now we can also improve conditions in our first if/else if block:
if (user1 == 1)
cout << "You chose ROCK!" << endl;
else if (user1 == 2)
cout << "You chose PAPER!" << endl;
else if (user1 == 3)
cout << "You chose SCISSORS!" << endl;
Which means we also can compare user1 to user2 so we know who won.
if (user1 == user2) {
cout << "It's a TIE!" << endl;
}
else if ((user1 == 1 && user2 == 2) ||
(user1 == 2 && user2 == 3) ||
(user1 == 3 && user2 == 1)) {
cout << "You LOSE!" << endl;
}
else {
cout << "You WIN!" << endl;
}
However, using 1, 2 and 3 does not make things very clear. What if you used an enum to represent these values?
enum RPSChoice
{
ROCK = 1,
PAPER = 2,
SCISSORS = 3
};
For example, the first block now looks like:
if (user1 == ROCK)
cout << "You chose ROCK!" << endl;
else if (user1 == PAPER)
cout << "You chose PAPER!" << endl;
else if (user1 == SCISSORS)
cout << "You chose SCISSORS!" << endl;
What if we wrapped our new two first blocks into a function so we avoid repeating ourselves?
void printDecision(string who, int choice) {
cout << who; // no matter what, we will tell who took a decision
if (choice == ROCK)
cout << " chose ROCK!" << endl;
else if (choice == PAPER)
cout << " chose PAPER!" << endl;
else if (choice == SCISSORS)
cout << " chose SCISSORS!" << endl;
}
This way, we can make playRPS even more clear, by replacing the two large blocks into simple, short function calls:
printDecision("You", user1);
printDecision("The computer", user2);
Let's do another simple function that decides who won:
int winner(int user1, int user2) {
if (user1 == user2) {
return 0; // tie
}
else if ((user1 == ROCK && user2 == PAPER) ||
(user1 == PAPER && user2 == SCISSORS) ||
(user1 == SCISSORS && user2 == ROCK)) {
return 2; // user2 is the winner
}
else {
return 1; // user1 is the winner
}
}
And a final one that returns the value we give according to a given character:
int characterToChoice(char c)
{
c = tolower(c);
if (c == 'r')
return ROCK;
else if (c == 's')
return SCISSORS;
else if (c == 'p')
return PAPER;
else
return 0; // Not a proper choice!
}
Done! This is the final program with all improvements in (nothing done to replace rand() in), and here is an online prompt to try it out.
Note that there are more ways you can improve the code, to simplify it even more and to make it more clear. I am most notably thinking about std::unordered_map to bind a RPSChoice value to a string, and a char to a RPSChoice. You may also prefer switch to if in some cases.
As stated by the comments to your question, you could have diagnosed this issue using a debugger. πάντα ῥεῖ's comment for reference:
The right tool to solve such problems is your debugger. You should step through your code line-by-line before asking on Stack Overflow. For more help, please read How to debug small programs (by Eric Lippert).

I am doing the program the subtracting game (NIM) in one of my exercises its asking me for another loop around the main loop

// Exercise2.5.3.cpp : Defines the entry point for the console application.
// Revising of the program so that it keeps playing the game until the user wants to quit.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char ans;
char stop;
do
{
int total, n;
cout << "Welcome to NIM. Pick a starting total: ";
cin >> total;
while (total < 1){
cout << "Enter positive integer only. ";
cout << "Pick starting total: ";
cin >> total;
}
while (true) {
// Pick best reponse and print results.
if ((total % 3) == 2) {
total = total - 2;
cout << "I am subtracting 2. " << endl;
}
else {
total--;
cout << "I am subtracting 1." << endl;
}
cout << "New total is " << total << endl;
if (total == 0){
cout << "I win!" << endl;
break;
}
// Get user's response; must be 1 or 2.
cout << "Enter num to subtract (1 or 2): ";
cin >> n;
while (n < 1 || n > 2) {
cout << "Input must be 1 or 2." << endl;
cout << "Re-enter: " << endl;
cin >> n;
}
total = total - n;
cout << "New total is " << total << endl;
if (total == 0) {
cout << "You win!" << endl;
break;
}
}
cout << "Do you want to continue (Y/N)?\n";
cout << "You must type a 'Y' or an 'N'.\n";
cin >> ans;
} while ((ans != 'Y') && (ans != 'N') && (ans != 'y') && (ans != 'n') && (stop != "0"));
return 0;
}
It gives a error after I run / compile the code 1 IntelliSense: operand types are incompatible ("char" and "const char *")
Do I have to use a do while loop or a while loop around my main loop in order for the program to work correctly and executes exactly what is asking ?? so that the program keeps playing the game until the user wants to quit ??
This is the program I try with the do while loop but is not working correctly exactly how it wants to work.
You declare:
char stop;
then use a "0" here:
} while ((ans != 'Y') && (ans != 'N') && (ans != 'y') && (ans != 'n') && (stop != "0"));
Try '0' because:
"0" is a const char *
'0' is a const char
Or since you never use stop, just remove it:
} while ((ans != 'Y') && (ans != 'N') && (ans != 'y') && (ans != 'n'));