Are there identifiers for strings or numbers? - c++

I recently developed a calculator, this is the code:
/*
*All 4 operations + percentage finder + Raise to power and more....
* by Ulisse
* ulissebenedennti#outlook.com
* Feel free to take some parts of this code an put them
* in yours, but do not take all the code and change/delete
* the comments to take the credit, trust me, it doesn't
* gives the satisfaction you expect.
*/
#include <iostream> //For cin and cout
#include <iomanip> //For setprecision()
#include <windows.h> //For SetconsoleTitle()
#include <stdlib.h> //For system()
#include <cmath> //For pow()
#include <cctype> //For isdigit()
using namespace std;
int main(){
reset:
system("cls"); //Screen cleaner
system("color 0f");
SetConsoleTitle("Calculator by Ulisse");//Setting window title
char op; //Start of the variables declaration
double a, b, ra;
string p, ms, d, me, e;
p = " + ";
ms = " - ";
d = " : ";
me = " x ";
e = " = "; //End of the variable declaration
cout << "Type now '?' for help page, or another character to continue." << endl;
cin >> op;
if (op == '?'){
help:
system("cls");
cout << "Write the whole operation.\nEXAMPLE: 2 ^ 3 \n OUTPUT: 2 ^ 3 = 8"<< endl;
cout << "(+) Sum between a and b\n(-) Subtraction between a and b" << endl;
cout << "(^) Raise to power\n(%)finds the a% of b\n(x or *)Multiplicate a by b" << endl;
cout << "(: or /) Divide a by b" << endl;
system("pause");
system("cls");
goto start;
}
else{
system("cls");
while(1){
start:
cout << "CALC> ";
cin >> a;
cin >> op;
cin >> b;
//The four operations
if (op == '+'){
cout << "RESULT" << endl;
cout << setprecision(999) << a << p << b << e << a + b << endl;
cout << "________________________________________________________________________________" << endl;
}
if (op == '-'){
cout << "RESULT" << endl;
cout << setprecision(999) << a << ms << b << e << a - b << endl;
cout << "________________________________________________________________________________" << endl;
}
if (op == '*' || op == 'x'){
cout << "RESULT" << endl;
cout << setprecision(999) << a << me << b << e << a * b << endl;
cout << "________________________________________________________________________________" << endl;
}
if (op == '/' || op == ':'){
cout << "RESULT" << endl;
cout << setprecision(999) << a << d << b << e << a / b << endl;
cout << "________________________________________________________________________________" << endl;
}
if (op == '%'){
cout << "RESULT" << endl;
cout << setprecision(999) << "The " << a << "% of " << b << " is " << b / 100 * a << endl;
cout << "________________________________________________________________________________" << endl;
}
if (op == '^'){
cout << "RESULT" << endl;
cout << setprecision(999) << a << " ^ " << b << " = " << pow (a, b) << endl;
cout << "________________________________________________________________________________" << endl;
}
//Some useful functions
if (op == 'c'){
system("cls");
}
if (op == '?'){
system("cls");
goto help;
}
if (op == 'r'){
goto reset;
}
if (op == 'b'){
system("color 0c");
Beep(400,500);
cout << "CLOSING, ARE YOU SURE?(y/n)";
system("color 0c");
cin >> op;
if(op == 'y'){
cout << "Closing..." << endl;
system("cls");
system("color 0f");
system("pause");
break;
}
if(op == 'n'){
goto start;
}
}
if (op == '<'){
if (a < b){
cout << "RESULT" << endl;
cout << setprecision(999) << a << " < " << b << e << " TRUE " << endl;
cout << "________________________________________________________________________________" << endl;
}
else{
cout << "RESULT" << endl;
cout << setprecision(999) << a << " < " << b << e << " FALSE " << endl;
cout << "________________________________________________________________________________" << endl;
}
}
if (op == '>'){
if (a > b){
cout << "RESULT" << endl;
cout << setprecision(999) << a << " > " << b << e << "TRUE" << endl;
cout << "________________________________________________________________________________" << endl;
}
else{
cout << "RESULT" << endl;
cout << setprecision(999) << a << " > " << b << e << "FALSE" << endl;
cout << "________________________________________________________________________________" << endl;
}
}
if (op == '='){
if (a == b){
cout << "RESULT" << endl;
cout << setprecision(999) << a << " = " << b << " is TRUE" << endl;
cout << "________________________________________________________________________________" << endl;
}
else{
cout << "RESULT" << endl;
cout << setprecision(999) << a << " = " << b << " is FALSE" << endl;
cout << "________________________________________________________________________________" << endl;
}
}
}
}
}
This is how it works:
You write a number, then an operator(like +, - plus other functions...) and it makes the operation between the two numbers you typed depending o what is the typed operato, so if you type 4 + 3 it will output 4 + 3 = 7.
Now that you understand how it works, let us go to the qyestion...
Is there an indentifier for a number or a character? When you type a sttring or a character when you cin >> (not a number variable) the application will start printing out characters that you did never inserted:
Input
I think like this(console output) will be printed out(until you dont close the process.
So i would like to prevent the applicatin for failing when you type an invalid input for the variable and making it executes another instruction, here's what i mean:
if(anumbervariable != number || anumbervariable == string){
cout << "invalid input" << endl;
}
This isn't a real working code, it's just a representation of what i mean, or i wouldn't came hre to make you waste you lives :)
Thanks in advance.

You can do something like follows
int getNumber(){
int x;
cin >> x;
while(cin.fail()){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "invalid input"<<endl;
cin >> x;
}
return x;
}
If you want to do a character by character thing, C++ has an isalpha() function, so you can use !isalpha(). The numeric limits thing is the max buffer that can be taken before a new line. If you print it out, it's just some large number so that it can ignore that amount of input.

Related

Incorrect user input

Trying to let only numbers be a vaild input for a quadratic equation solver. I used bool and broke my code and no matter the input it just gives me my error message even if it is a vaild input.
After the progarm ask you to confirm the coefficients are correct, even if you put Y you get the " Please input a number. Please try again". how do you fix this?
I added the bool becasue that what my teacher showed me to use for checking inputs, very new to c++ and coding. I just added the whole code, the HW was to update HW 5 to do a few things more. I broke it trying to check inputs, when adding bool.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string first, last;
double a, b, c, x1, x2, discriminant, realpart, imaginarypart;
char ch;
cout << "Please enter First and Last name," << endl;
cout << " " << endl;
cout << "First Name= ";
cin >> first;
cout << "and" << endl;
cout << "Last Name=";
cin >> last;
cout << " " << endl;
cout << " Hello " << first << " " << last << " "
<< "welcome." << endl;
cout << " " << endl;
bool isCorrect{ true };
do {
start:
isCorrect = true;
cout << "Enter the coefficients of a: ";
cin >> a;
cout << " " << endl;
cout << "Enter the coefficients of b: ";
cin >> b;
cout << " " << endl;
cout << "Enter the coefficient of c: ";
cin >> c;
cout << " " << endl;
cout << " A = " << a;
cout << " B = " << b;
cout << " C = " << c << endl
<< endl;
cout << " Confirm the coefficients value are correct or not (y/n): " << endl;
cout << " " << endl;
cin >> ch;
if (ch == 'n' || ch == 'N')
goto start;
cout << " " << endl;
discriminant = b * b - 4.0 * a * c;
if (cin.fail())
;
{
isCorrect = false;
cin.clear();
cin.ignore(245, '\n');
cout << " Please input a number. Please try again" << endl;
}
} while (!isCorrect);
bool isExit(false);
if (a == 0) {
cout << " " << endl;
cout << "Error message: a can not = zero (0) " << endl;
}
else if (discriminant > 0) {
x1 = (-b + sqrt(discriminant)) / (2.0 * a);
x2 = (-b - sqrt(discriminant)) / (2.0 * a);
cout << "Roots are real and different." << endl;
cout << " " << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 =" << x2 << endl;
}
else if (discriminant == 0) {
cout << "Roots are real and same." << endl;
cout << " " << endl;
x1 = -b / (2.0 * a);
cout << "x1 = x2 ="
" "
<< x1 << endl;
}
else {
//cout << "Error message: No real solution exist." << endl; // Part 1 error code for no real solutions
realpart = -b / (2.0 * a); //Code for part 2
imaginarypart = sqrt(-discriminant) / (2.0 * a); // Code for part 2
cout << "Roots are complex and different." << endl; // Code for part 2
cout << " " << endl;
cout << "x1 = " << realpart << "+" << imaginarypart << "i" << endl; // Code for part 2
cout << "x2 = " << realpart << "-" << imaginarypart << "i" << endl; // Code for part 2
}
cout << " " << endl;
cout << " Would you like to solve another quadratic equation (y/n): " << endl;
cin >> ch;
if (ch == 'y' || ch == 'Y')
goto start;
else
(ch == 'n' || ch == 'N');
return 0;
}

I am having problem with my Sudoku program with some error codes

I am writing in C++ and the errors I am having are:
E0120 return value type does not match the function type
C4700 uninitialized local variable 'name' used
C2562 interact 'void function returning a value
And a warning error of C4447.
My code is down below:
#include <limits>
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
void readFile(char sudokuBoard[][9]);
void writeFile(char sudokuBoard[][9]);
void display(char sudokuBoard[][9]);
void interact();
void getOption(char sudokuBoard[][9]);
void editSquare(char sudokuBoard[][9]);
void showValues();
void openingMessage();
void openingQuestion();
//opening message to the game and pause
void openingMessage()
{
std::cout << "Welcome to Sudoku"
<< endl << "Press any key to continue.";
cin.ignore();
}
//Questions to determine whether the user will play the game
void openingQuestion()
{
char response; // users input to the question below
cout << "Would you like to play Sudoku ? " << endl << "1 for yes, 2 for no";
cin >> response;
if (response == 1) //if there answer is yes
{
//return main();
}
else if (response == 2) //if answer is no
{
cout << "are you sure you do not want to play ?" << endl << "1 for yes and 2 for no";
//if user answers no
char eResponse; //response to the next question
if (eResponse == 2) // 2 equals no
{
return main();
}
// if user answers yes
if (eResponse == 1) // 1 equals yes
{
//return exit();
}
}
}
//Makes other functions function
int main()
{
//Declaring array
char sudokuBoard[9][9];
//calling the other functions
readFile(sudokuBoard);
interact();
display(sudokuBoard);
return 0;
}
//Asks the user for a fulename to read a gamebaord
//in from that file name and then places it in an array
void readFile(char sudokuBoard[][9])
{
//Declare filename
char sourceFile[256];
//Declaring file input
ifstream fin;
//Getting the filename from the user
cout << "Where is your board located? ";
cin >> sourceFile;
//Open file error checking
fin.open(sourceFile);
if (fin.fail())
{
cout << "Input file opening failed. " << endl;
exit(1);
}
//Read file into array
for (int col = 0; col < 9; col++)
{
for (int row = 0; row < 9; row++)
{
fin >> sudokuBoard[row][col];
if (sudokuBoard[row][col] == '0')
{
sudokuBoard[row][col] = ' ';
}
}
}
//close the file
fin.close();
}
//displays the result to the screen
void display(char sudokuBoard[][9])
{
//Declare variables
char option;
//Display Column Title
cout << " A| B| C| D| E| F| G| H| I" << endl;
//Row 1
cout << "1 "
<< sudokuBoard[0][0]
<< " " << sudokuBoard[1][0]
<< " " << sudokuBoard[2][0]
<< "|"
<< sudokuBoard[3][0]
<< " " << sudokuBoard[4][0]
<< " " << sudokuBoard[5][0]
<< "|"
<< sudokuBoard[6][0]
<< " " << sudokuBoard[7][0]
<< " " << sudokuBoard[8][0]
<< endl;
//Row 2
cout << "2 "
<< sudokuBoard[0][0]
<< " " << sudokuBoard[1][1]
<< " " << sudokuBoard[2][1]
<< "|"
<< sudokuBoard[3][1]
<< " " << sudokuBoard[4][1]
<< " " << sudokuBoard[5][1]
<< "|"
<< sudokuBoard[6][1]
<< " " << sudokuBoard[7][1]
<< " " << sudokuBoard[8][1]
<< endl;
//Row 3
cout << "3 "
<< sudokuBoard[0][2]
<< " " << sudokuBoard[1][2]
<< " " << sudokuBoard[2][2]
<< "|"
<< sudokuBoard[3][2]
<< " " << sudokuBoard[4][2]
<< " " << sudokuBoard[5][2]
<< "|"
<< sudokuBoard[6][2]
<< " " << sudokuBoard[7][2]
<< " " << sudokuBoard[8][2]
<< endl;
//Separator
cout << " -----_-----_-----" << endl;
//Row 4
cout << "4 "
<< sudokuBoard[0][3]
<< " " << sudokuBoard[1][3]
<< " " << sudokuBoard[2][3]
<< "|"
<< sudokuBoard[3][3]
<< " " << sudokuBoard[4][3]
<< " " << sudokuBoard[5][3]
<< "|"
<< sudokuBoard[6][3]
<< " " << sudokuBoard[7][3]
<< " " << sudokuBoard[8][3]
<< endl;
//Row 5
cout << "5 "
<< sudokuBoard[0][4]
<< " " << sudokuBoard[1][4]
<< " " << sudokuBoard[2][4]
<< "|"
<< sudokuBoard[3][4]
<< " " << sudokuBoard[4][4]
<< " " << sudokuBoard[5][4]
<< "|"
<< sudokuBoard[6][4]
<< " " << sudokuBoard[7][4]
<< " " << sudokuBoard[8][4]
<< endl;
//Row 6
cout << "6 "
<< sudokuBoard[0][5]
<< " " << sudokuBoard[1][5]
<< " " << sudokuBoard[2][5]
<< "|"
<< sudokuBoard[3][5]
<< " " << sudokuBoard[4][5]
<< " " << sudokuBoard[5][5]
<< "|"
<< sudokuBoard[6][5]
<< " " << sudokuBoard[7][5]
<< " " << sudokuBoard[8][5]
<< endl;
//Separator
cout << " -----_-----_-----" << endl;
//Row 7
cout << "7 "
<< sudokuBoard[0][6]
<< " " << sudokuBoard[1][6]
<< " " << sudokuBoard[2][6]
<< "|"
<< sudokuBoard[3][6]
<< " " << sudokuBoard[4][6]
<< " " << sudokuBoard[5][6]
<< "|"
<< sudokuBoard[6][6]
<< " " << sudokuBoard[7][6]
<< " " << sudokuBoard[8][6]
<< endl;
//Row 8
cout << "8 "
<< sudokuBoard[0][7]
<< " " << sudokuBoard[1][7]
<< " " << sudokuBoard[2][7]
<< "|"
<< sudokuBoard[3][7]
<< " " << sudokuBoard[4][7]
<< " " << sudokuBoard[5][7]
<< "|"
<< sudokuBoard[6][7]
<< " " << sudokuBoard[7][7]
<< " " << sudokuBoard[8][7]
<< endl;
cout << "9 "
<< sudokuBoard[0][8]
<< " " << sudokuBoard[1][8]
<< " " << sudokuBoard[2][8]
<< "|"
<< sudokuBoard[3][8]
<< " " << sudokuBoard[4][8]
<< " " << sudokuBoard[5][8]
<< "|"
<< sudokuBoard[6][8]
<< " " << sudokuBoard[7][8]
<< " " << sudokuBoard[8][8]
<< endl
<< endl;
getOption(sudokuBoard);
}
//Allows the user to interact and manipulate the game board
void interact()
{
cout << "Options:" << endl
<< " ? Show these instructions" << endl
<< " D Display the board" << endl
<< " X Edit one square" << endl
<< " H Help show the possible values for one of the squares"
<< endl
<< " Q Save and Quit" << endl
<< endl;
return getOption;
}
//gets the user's input
void getOption(char sudokuBoard[][9])
{
char option;
cout << "> ";
cin >> option;
if (option == 'x' || option == 'X')
editSquare(sudokuBoard);
else if (option == '?')
interact();
else if (option == 'd' || option == 'D')
display(sudokuBoard);
else if (option == 'h' || option == 'H')
showValues();
else if (option == 'q' || option == 'Q')
writeFile(sudokuBoard);
else
cout << "ERROR: Invalid command";
return;
}
//edits one square with coordinates entered by the user
void editSquare(char sudokuBoard[][9])
{
//Declare variables
char letter;
int number;
int value = 0;
//Get letter and number coordinates
cout << "What are the coordinates of the square: ";
cin >> letter >> number;
//Converts letter to uppercase
letter = toupper(letter);
//if square is full, display "read only" message
if (sudokuBoard[letter - 65][number - 1] != ' ')
{
cout << "ERROR: square \'" << letter
<< number << "\' is a read-only" << endl;
getOption(sudokuBoard);
}
else
{
//get value to place in the coordinates
cout << "what is the value at \'" << letter
<< number << "\': ";
cin >> value;
//makes sure value is within the right range
if (value < 1 || value > 9)
{
cout << "Try Again: Value |'" << value << "| in square |'"
<< letter << number << "|' is invalud" << endl;
cout << endl;
getOption(sudokuBoard);
}
// Check for duplicate in column
for (int row = 0; row < 9; ++row)
if (sudokuBoard[row][number - 1] == value)
{
cout << "ERROR: square \'" << letter
<< number << "\' you typed a duplicate number" << endl
<< "Please try again" << endl;
}
// Check for duplicate in row
for (int col = 0; col < 9; ++col)
if (sudokuBoard[letter - 65][col] == value)
{
cout << "ERROR: square \'" << letter
<< number << "\' you typed a duplicate number" << endl
<< "Please try again" << endl;
}
cout << endl;
sudokuBoard[letter - 65][number - 1] = value;
getOption(sudokuBoard);
}
return;
}
//writes the content of the board to a file to be picked up later
void writeFile(char sudokuBoard[][9])
{
//File output
ofstream fout;
char destinationFile[256];
//user input
cout << "What file would you like to write your board to: ";
cin >> destinationFile;
//Open destination file & error checking
fout.open(destinationFile);
if (fout.fail())
{
cout << "Output file opening failed" << endl;
exit(1);
}
else
cout << "Board written successfully";
//Write board to file
for (int col = 0; col < 9; col++)
{
for (int row = 0; row < 9; row++)
{
if (sudokuBoard[row][col] == ' ')
{
sudokuBoard[row][col] = '0';
}
fout << sudokuBoard[row][col];
//Makes sure it's a 9x9 grid
if (row % 9 == 0)
{
fout << endl;
}
}
}
//close file
fout.close();
}
//Show all the possible values for a given coordinates
void showValues()
{
//variables
char letter;
int number;
//letter/number coordinates
cout << "What are the coordinates of the square: ";
cin >> letter >> number;
//Coinverts letter to uppercase
letter = toupper(letter);
return;
}
I am using Visual Studio 2019 for this.
A couple notes to point out
first of all, you can not return the main function
in your line
if (eResponse == 2) // 2 equals no
{
return main();
}
next
you have a lot of void function with return statements
because the function is void you can not return anything
instead of
void getOption(char sudokuBoard[][9])
{
char option;
cout << "> ";
cin >> option;
if (option == 'x' || option == 'X')
editSquare(sudokuBoard);
else if (option == '?')
interact();
else if (option == 'd' || option == 'D')
display(sudokuBoard);
else if (option == 'h' || option == 'H')
showValues();
else if (option == 'q' || option == 'Q')
writeFile(sudokuBoard);
else
cout << "ERROR: Invalid command";
return;
}
use
char getOption(char sudokuBoard[][9])
{
char option;
cout << "> ";
cin >> option;
if (option == 'x' || option == 'X')
editSquare(sudokuBoard);
else if (option == '?')
interact();
else if (option == 'd' || option == 'D')
display(sudokuBoard);
else if (option == 'h' || option == 'H')
showValues();
else if (option == 'q' || option == 'Q')
writeFile(sudokuBoard);
else
cout << "ERROR: Invalid command";
return option;
}
go through your functions and ask yourself, do i need to return a value? if yes then change from void to what ever type you are using and if no then remove the return statement.
for your warning issue
char sudokuBoard[9][9];
is not being initialised.
you can do something like
char sudokuBoard[9][9] = {};

While loop and boolean function

Hello guys I'm not an expert on the subject so please excuse my pour skills. I finished my program and it works fine (calculator). The problem is that now I don't know where to locate the while loop in conjunct with the Boolean function to repeat the process once it is done with a task (once the program completes a math operation). Any help, comment or suggestion will be greatly appreciated. Thank you.!!
#include <iostream>
#include <math.h>
#include <cmath>
int main()
{
double a=0.0;
double b=0.0;
double c=0.0;
bool repeat = true;
do {
using namespace std;
int x;
cout << "**********************************" << endl;
cout << "| |" << endl;
cout << "| 0 - Quit |" << endl;
cout << "| 1 - Add |" << endl;
cout << "| 2 - Subtract |" << endl;
cout << "| 3 - Divide |" << endl;
cout << "| 4 - Multiply |" << endl;
cout << "| 5 - Raise X to the power Y |" << endl;
cout << "| 6 - Sine ( x ) |" << endl;
cout << "| 7 - Cosine ( x ) |" << endl;
cout << "| 8 - Tangent ( x ) |" << endl;
cout << "**********************************" << endl;
cout << "Enter a selection, please: " << endl;
cin >> x;
switch (x)
{
{
case 1:
cout << " Enter the first value" <<endl;
cin >> a ;
cout << " Enter second value " << endl;
cin >> b;
c=a+b;
cout << "The addition of " << a << " and "<< b << "is" << c << endl;
break;
bool repeat = true;
}
{
case 2:
cout << " Enter the first value" << endl;
cin >> a ;
cout << " Enter the second value " << endl;
cin >> b;
c=a-b;
cout << "The subtraction of " << a << " and " << b << " is: " << c << endl;
break;
bool repeat = true;
}
{
case 3:
cout << " Enter the first value" <<endl;
cin >> a ;
cout << " Enter the second value " << endl;
cin >> b;
c=a/b;
cout << " The division os " << a << " and " << b << "is" << c << endl;
break;
bool repeat = true;
}
{
case 4:
cout << " Enter the first value" <<endl;
cin >> a ;
cout << " Enter the second value " << endl;
cin >> b;
c=a*b;
cout << " The product of " << a << " times " << b << " is " << c << endl;
break;
bool repeat = true;
}
{
case 5:
cout << " Enter the value to be exponentiated " <<endl;
cin >> a ;
cout << " Enter the exponent" << endl;
cin >> b;
c= pow(a,b);
cout << a << " Rased to the power of " << b << " is: " << c << endl;
break;
bool repeat = true;
}
{
case 6:
cout << " Enter the value that you want the sine to be taken of" <<endl;
cin >> a ;
c=sin(a);
cout << " The sine of " << a << " is: " << c << endl ;
break;
bool repeat = true;
}
{
case 7:
cout << " Enter the value that you want the cosine to be taken of" <<endl;
cin >> a ;
c=cos(a);
cout << " The cosine of " << a << " is: " << c << endl ;
break;
bool repeat = true;
}
{
case 8:
cout << " Enter the value that you want the tangent to be taken of" <<endl;
cin >> a ;
c=tan(a);
cout << " The tangent of " << a << " is: " << c << endl ;
break;
bool repeat = true;
}
{
case 0:
cout << "Ending the program" << endl;
return 0;}
break;
bool repeat = true;
}
} while (repeat = true );
return 0;
}
So here is few moments.
Call
using namespace std;
just believe - is bad idea;
In conditions like if() or while() use operator == instead of =. Because "=" - is assigne operator, and return value depended on success of operation. And "==" is compare operator.
Ow and figure one more missunderstanding. Using bool rezult = true; is wrong. You should use rezult = true; Because every time when you write type specifer you create local variable in context of case, and this don`t affect rezult declared in main
My opinion for your question is little change:
from:
do{
int x;
...
case 0:
cout << "Ending the program" << endl;
return 0;}
break;
bool repeat = true;
}
} while (repeat = true );
to
do{
int x;
...
case 0:
cout << "Ending the program" << endl;
repeat = false;}
break;
}
} while (repeat == true);
and if you need a bit more calculations you can wrapped it to new cicle something like:
while(new_condtion == true) {
do {
...
} while(repeat == true);
//change new_condtion
}
Don't redefine repeat within switch case. This creates a different variable named repeat which, although it has the same name, is not the variable named repeat defined before the loop. This is what you get when you copy a definition of the form bool repeat = true; into multiple places.
The continuation condition for the loop (repeat = true) will also loop forever. Comparison is two = signs, not one.

Scorecard Hangman. C++

Right now I am trying to get my scorecard to work for hangman. This is a game I can play as many times as I want and I want it to show my lowest score when I press 2 at the game menu. For some reason my logic isn't working. Can anyone help? I have attached the 3 sections of code necessary for this to work.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <fstream>
using namespace std;
int maxAttempts = 10; //max attempts possible
void poorStiff(int);
int wordFill(char, string, string&);
int main()
{
int intro;
int bodyPart = 0;
ifstream wordIn; //file stream read in
wordIn.open("WordList.txt"); //list of words used in this game
//if (!wordIn.good()) { std::cerr << "open failed.\n"; exit(1); }
char letter; //letter guessed
int numWrongGuesses = 0; //counts the number of wrong guesses
string theWord;
string words[13];
int play = 0;
bool run = true;
int makeYourSelection = 0;
int bestScore = 11;
while (run == true)
{
int attemptsGame = 0;
// put a game menu to loop that asks if you want to keep playing or exit and go to scorecard
cout << " WELCOME TO THE GAME OF HANGMAN\n\n\n\n";
cout << " Press 1 to play the game, press 2 to exit to the scorecard \n\n";
cout << " You have 10 attempts to guess the words before you get hung \n\n";
cin >> play;
while (play == 1)//loops while user has entered 1, 0 exits the game
{
for (int i = 0; i < 13; i++) //labeled 13 and not words because 13 is a constant
{
wordIn >> words[i];//replaces the file words and puts them in an array and counts them out of the file
cout << words[i] << endl;
}
srand(time(NULL));//to get a random word
int n = rand() % 12;
theWord = words[n]; //pulls word from file
wordIn.close();
string mystery(theWord.length(), '*'); //replaces word letters with asterisks
while (numWrongGuesses < maxAttempts) // while the amount of guesses is less than the max wrong guesses
{
cout << mystery << endl << endl;
cout << "You now have the length of the word represented by the *'s. \n\n";
cout << "Guess a letter \n\n";
cin >> letter;
if (wordFill(letter, theWord, mystery) == 0) //fuction call
{
bodyPart++;
poorStiff(bodyPart);
cout << "You have entered a letter that isn't in the word, guess again. \n\n";
numWrongGuesses++;
attemptsGame++;
}
else
{
for (int i = 0; i < mystery.length(); i++)
{
if (theWord[i] == letter)
{
mystery[i] = letter;
}
}
cout << "You have found one of the letters. Congratulations! \n\n";
cout << "You have: " << maxAttempts - numWrongGuesses;
cout << " guesses left \n\n" << endl;
}
if (theWord == mystery) // the word is the same as mystery
{
cout << theWord << endl;
cout << "\n\n Awesome, you guessed it. \n\n";
break;
if (attemptsGame < bestScore)
{
bestScore = attemptsGame;
}
}
}
if (numWrongGuesses == maxAttempts) //when you run out of guesses
{
cout << "Too bad, you ran out of guesses and have been hung at the gallows. \n\n";
cout << "The word you were trying to guess was " << theWord << endl;
poorStiff(bodyPart);
}
cin.ignore();
cin.get();
break;
}
while (play == 2)
{
cout << "Best Scores: \n\n";
cout << bestScore << endl;
system("pause");
return 0;
break;
}
}
system("pause");
return 0;
}
int wordFill(char guess, string theWordSecret, string&guessWord) //function for determing if you guess a letter contained
{
int i;
int hits = 0; //letter hits within the word
int many = theWordSecret.length();
for (i = 0; i < many; i++)
{
if (guess == guessWord[i])
return 0;
if (guess == theWordSecret[i])
{
guessWord[i] == guess;
hits++;
}
}
return hits;
}
void poorStiff(int bodyPart)
{
if (bodyPart == 1)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 2)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| |" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 3)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 4)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|" << endl;
cout << "| / " << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 5)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|" << endl;
cout << "| / |" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 6)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|\." << endl;
cout << "| / | \." << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 7)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|\." << endl;
cout << "| / | \." << endl;
cout << "| /" << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 8)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|\." << endl;
cout << "| / | \." << endl;
cout << "| / \." << endl;
cout << "|" << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 9){
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|\." << endl;
cout << "| / | \." << endl;
cout << "| / \." << endl;
cout << "| / " << endl;
cout << "_______________" << endl;
}
else if (bodyPart == 10)
{
cout << "_______" << endl;
cout << "| }" << endl;
cout << "| O" << endl;
cout << "| /|\." << endl;
cout << "| / | \." << endl;
cout << "| / \." << endl;
cout << "| / \." << endl;
cout << "_______________" << endl;
}
}
Did you try debugging? If you step through your code you will immediately find the problem, which is here:
if (theWord == mystery) // the word is the same as mystery
{
cout << theWord << endl;
cout << "\n\n Awesome, you guessed it. \n\n";
break; // problem here
if (attemptsGame < bestScore)
{
bestScore = attemptsGame;
}
// break should be here
}
You're breaking out of your loop before your checking logic. So move your break statement to after the check, because that code never gets executed.
For a start enable your compiler warnings, you'll get many from a quick look at your code.
Change this
guessWord[i] == guess;
to this
guessWord[i] = guess;
At this point
if (wordFill(letter, theWord, mystery) == 0) //fuction call
{
...
cout << "You have entered a letter that isn't in the word, guess again. \n\n";
}
else
{
...
if (theWord == mystery) // the word is the same as mystery
{
cout << theWord << endl;
cout << "\n\n Awesome, you guessed it. \n\n";
break;
...
}
}
Here, when you are entering the first if, then you will enter the second if too, which doesn't make sense. That happens because theWord and mystery are both empty strings!
Also notice that break should be after this part of code:
if (attemptsGame < bestScore)
{
bestScore = attemptsGame;
}
because as it is, this part of code will never be executed.
I suggest taking at this answer (not relevant with your logical error)
System(“pause”); - Why is it wrong?

Why doesn't my game loop execute

I have started with C++ and I am in the middle of creating a hangman game, My code worked fine up until I chose to make three different levels of difficulty, My game asks the user for the difficulty level they would like to play, then instead of actually playing the game, it skips straight to the end where it says the user has guessed the word correctly. Any help appreciated!
The code is as follows :
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cctype>
using namespace std;
void ClearScreen();
void DisplayMan0();
void DisplayMan1();
void DisplayMan2();
void DisplayMan3();
void DisplayMan4();
void DisplayMan5();
void DisplayMan6();
void DisplayMan7();
int main()
{
const int MAX_WRONG = 7; // incorrect guesses allowed
void (*pfnaDisplayMan[])() = {DisplayMan0, DisplayMan1, DisplayMan2, DisplayMan3, DisplayMan4, DisplayMan5, DisplayMan6, DisplayMan7};
vector<string> words; // Level 1
words.push_back("GREEN");
words.push_back("BANANA");
words.push_back("LAPTOP");
words.push_back("GIRAFFE");
words.push_back("PENCIL");
vector<string> wordsD1; // Level 2
wordsD1.push_back("DELICIOUS");
wordsD1.push_back("COMPUTING");
wordsD1.push_back("SOFTWARE");
wordsD1.push_back("HARDWARE");
wordsD1.push_back("TELEPHONE");
vector<string> wordsD2; // Level 3
wordsD2.push_back("BAMBOOZLED");
wordsD2.push_back("DAYDREAMER");
wordsD2.push_back("CANNIBALISM");
wordsD2.push_back("NERVOUSLY");
wordsD2.push_back("APPROACHING");
srand((unsigned int)time(0));
string THE_WORD;
string soFar;
int wordLength;
string used; // letters already guessed
cout << "\t\t HANGMAN\n";
cout << "Please enter a difficulty level [1-3] ";
int dif = 0;
while(dif < 1 || dif > 3)
{
cin >> dif;
}
cout << "You have chosen difficulty level : "<< dif << endl;
if(dif == 1)
{
random_shuffle(words.begin(), words.end());
int incorrectGuesses = 0; // number of incorrect guesses
string const THE_WORD = words[0]; // word to guess
string soFar(THE_WORD.size(), '*'); // word guessed so far
// count length of randomly chosen string and display it
wordLength = THE_WORD.length();
}
if(dif == 2)
{
random_shuffle(wordsD1.begin(), wordsD1.end());
int incorrectGuesses = 0; // number of incorrect guesses
string const THE_WORD = wordsD1[0];
string soFar(THE_WORD.size(), '*');
wordLength = THE_WORD.length();
}
if(dif == 3)
{
random_shuffle(wordsD2.begin(), wordsD2.end());
int incorrectGuesses = 0; // number of incorrect guesses
string const THE_WORD = wordsD2[0];
string soFar(THE_WORD.size(), '*');
wordLength = THE_WORD.length();
}
// main loop
while ((incorrectGuesses < MAX_WRONG) && (soFar != THE_WORD))
{
cout << "\n- There are : "<< wordLength <<" letters in the word :\t" << soFar << endl;
cout << "\n- You have guessed " <<incorrectGuesses << " times wrong out of "<< MAX_WRONG << " allowed wrong guesses.\n";
cout << "\nLetters used : " << used << endl;
cout << "=====================================================";
char guess;
cout << "\n\t\tEnter a letter : ";
cin >> guess;
guess = toupper(guess); //make uppercase since secret word in uppercase
while (used.find(guess) != string::npos)
{
cout << "\nYou've already guessed the letter " << guess << endl;
cout << "Enter another letter / word: ";
cin >> guess;
guess = toupper(guess);
}
used += guess;
if (THE_WORD.find(guess) != string::npos)
{
cout << "=====================================================\n";
cout << "- Correct, The letter " << guess << " is in the word.\n";
// update soFar to include newly guessed letter
for (int i = 0; i < THE_WORD.length(); ++i)
if (THE_WORD[i] == guess)
soFar[i] = guess;
}
else
{
cout << "Sorry, " << guess << " isn't in the word.\n";
++incorrectGuesses;
pfnaDisplayMan[incorrectGuesses]();
}
}
// shut down
if (incorrectGuesses == MAX_WRONG)
cout << "\nYou've been hanged!";
else
cout << "\nYou guessed it!";
cout << "\nThe word was " << THE_WORD << endl;
return 0;
}
void DisplayMan0()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan1()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan2()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan3()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan4()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X\\" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan5()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X\\" << endl;
cout << "| /" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan6()
{
using namespace std;
cout << "_______" << endl;
cout << "| |" << endl;
cout << "| o" << endl;
cout << "| /X\\" << endl;
cout << "| / \\" << endl;
cout << "|" << endl;
cout << "|" << endl;
cout << "________" << endl;
}
void DisplayMan7()
{
using namespace std;
cout << "\t\t_______" << endl;
cout << "\t\t|DONT" << endl;
cout << "\t\t|HANG" << endl;
cout << "\t\t|THE" << endl;
cout << "\t\t|MAN" << endl;
cout << "\t\t| O" << endl;
cout << "\t\t| _______ /XL" << endl;
cout << "\t\t__|_____| / \\" << endl;
}
Put incorrectGuesses out of those scopes. Because out of those scopes this variable is not declared.
if(dif == 1)
{
int incorrectGuesses = 0;
...
}
if(dif == 2)
{
int incorrectGuesses = 0;
...
}
if(dif == 3)
{
int incorrectGuesses = 0;
...
}
Should be
int incorrectGuesses = 0;
if(dif == 1)
{
...
}
if(dif == 2)
{
...
}
if(dif == 3)
{
...
}
Same issues for soFar, THE_WORD and wordLength. That part of code should be like this:
string THE_WORD;
string soFar;
int wordLength;
string used;
// cout ... cin ....
int incorrectGuesses = 0;
if(dif == 1)
{
random_shuffle(words.begin(), words.end());
THE_WORD = words[0]; // word to guess
wordLength = THE_WORD.length();
}
if(dif == 2)
{
random_shuffle(wordsD1.begin(), wordsD1.end());
THE_WORD = wordsD1[0];
wordLength = THE_WORD.length();
}
if(dif == 3)
{
random_shuffle(wordsD2.begin(), wordsD2.end());
THE_WORD = wordsD2[0];
wordLength = THE_WORD.length();
}
soFar.assign(THE_WORD.size(), '*');
M M. is correct. Your redeclaring the variables.
Just a small remark. I would use a Switch Case instead of a set of if statements. Changing:
if(dif==1){}
if(dif==2){}
if(dif==3){}
into
switch(dif){
case(1):
break;
case(2):
break;
case(3):
break;
}
Not for necessarily for readability but more to indicate that the value of dif isn't edited depending upon its value. For example:
Option 1:
dif = 1;
if(dif==1){ dif = 3; }
if(dif==2){}
if(dif==3){ dif = 7; }
Versus:
Option 2
dif = 1;
switch(dif){
case(1):
dif = 3;
break;
case(2):
break;
case(3):
dif = 7;
break;
}
Option 1 output: 7
Option 2 output: 3
You declare incorrectGuesses out of scope. It is NEVER declared or assigned a value. Declare it at the beginning of your function and assign it value in the other scopes.