im working on a project for school where we are supposed to create a Contact book.
I stumbled on to a problem where my program prints out strings as hexa symbols, i have never encountered this before and have no idea on how to combat it.
The strings are getting printed out on the terminal from an array.
#include <iostream>
#include <string>
using namespace std;
const int unikapersoner = 75;
string I_namn[unikapersoner];
string T_Nummer[unikapersoner];
void addcontact() {
char Fullname[50];
char TelefonNummer[50];
cin.ignore();
cout << "Ange det fullständiga namnet du vill spara till kontaktboken.. "
<< endl;
cin.getline(Fullname, 50);
cout << "Ange telefonnummeret till personen som du vill spara.. " << endl;
cin.getline(TelefonNummer, 50);
for(int i = 0; i < unikapersoner; i++) {
if(T_Nummer[i] == "\0") { // Letar efter tom index.
I_namn[i] = Fullname;
T_Nummer[i] = TelefonNummer;
break;
}
}
}
void listALLcontacts() {
cout << "/Kontakter/." << endl;
cout << "=================================" << endl;
int nr = 0;
for(int i = 0; i < unikapersoner; i++) {
if(T_Nummer[i] != "\0") {
nr++;
cout << "#" << nr << " " << I_namn << " " << T_Nummer << endl;
cout << "- - - - - - - - -" << endl;
}
}
cout << "=================================" << endl;
if(nr == 0) {
cout << "Du har inga kontakter i din telefonbok..";
}
}
int main() {
int terminalval;
system("CLS");
do {
cout << "Din telefonbok!" << endl;
cout << "1 : Ange ny Kontakt" << endl;
cout << "2 : Se nuvarande Kontakter" << endl;
cout << "3 : Uppdatera kontakt" << endl;
cout << "4 : Radera kontakt" << endl;
cout << "5 : Avsluta" << endl;
cout << "Ange ditt val.." << endl;
cin >> terminalval;
switch(terminalval) {
case 1:
addcontact();
break;
case 2:
listALLcontacts();
break;
case 3:
updatecontacts();
break;
case 4:
deletecontact();
break;
default:
cout << "Är ett felaktigt kommando! " << endl;
}
} while(terminalval != 5);
}
Some outputs could for example be "#1 0x123123fb123 0x213g2134z13"
I would as always appreciate all the help i could get!
Thank you.
You are printing the addresses of the arrays I_namn and T_Nummer in the function listALLcontacts here:
cout << "#" << nr << " " << I_namn << " " << T_Nummer << endl;
You should use the index, i, to print the found entry:
cout << "#" << nr << " " << I_namn[i] << " " << T_Nummer[i] << endl;
A note unrelated to the problem you asked about:
You do a few comparisons like this
if(T_Nummer[i] == "\0")
which isn't needed. "\0" is actually 2 chars long, consisting of the \0 you've put there and then a terminating \0, so just do
if(T_Nummer[i] == "")
or even better:
if(T_Nummer[i].empty())
Related
Im writing a wordle game and am trying to get the output to work, but i have no clue as to what im doing wrong here. The basic version of the code is 5 letter words are taken from a word file and stored in an array, then a random word is picked from there to be the answer to the wordle. Then the user is prompted for input and once they input a word, it verifies the length, as well as if it is in the array of words. then another function takes the guessed word and compares it against the winning word and outputs the guessed word with colors to show what letters are in the right spot, like real wordle. The issue arises when i try to print everything out, i tried to use a while loop to ask for input but i couldnt get it to work so i decided to test it by making a function that asks for the input, then i called it six times, each time giving it a different variable to store the result in, then print out the first one on the first guess, the first and second on the second guess, and so on. But it only prints out the current guess. It might be something very obvious but i have spent so much time coding i have no idea. any help is greatly appreciated.
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
using namespace std;
const string CORRECT = "\033[7;32m";
const string CLOSE = "\033[7;33m";
const string INCORRECT = "\033[7;37m";
const string END = "\033[0m";
int verifyExists(string word, string verifyArr[2315]) {
if (word.size() == 5)
{
for (int i = 0; i < 2315; i++)
{
if (word == verifyArr[i])
{
return 1;
}
}
return 2;
} else {
return 3;
}
}
string buildResult(string plyrGuess, string word)
{
string result[5];
string color;
for (int i = 0; i < 5; i++){
if (plyrGuess[i] != word[i])
{
color = INCORRECT + plyrGuess[i] + END;
result[i] = color;
}
if ((plyrGuess[i] != word[i]) && (plyrGuess[i] == word[0] || plyrGuess[i] == word[1] || plyrGuess[i] == w\
ord[2] || plyrGuess[i] == word[3] || plyrGuess[i] == word[4]))
{
color = CLOSE + plyrGuess[i] + END;
result[i] = color;
}
if (plyrGuess[i] == word[i])
{
color = CORRECT + plyrGuess[i] + END;
result[i] = color;
}
}
string done;
for (int i = 0; i < 5; i++)
{
cout << result[i];
}
getline(cin, done);
return done;
}
string askInput(string array[2315])
{
string guessWord;
cout << "What word would you like to guess?" << endl;
getline(cin, guessWord);
while (verifyExists(guessWord, array) == 2)
{
cout << "The word: " << guessWord << " is not in the word list" << endl;
getline(cin, guessWord);
}
while (verifyExists(guessWord, array) == 3)
{
cout << "You must enter a word that is 5 letters in length: " << endl;
getline(cin, guessWord);
}
return guessWord;
}
void playGame(string winWord, string arr[2315]) {
cout << "Ok. I am thinking of a word with 5 letters." << endl;
string guess1 = askInput(arr);
string done1 = buildResult(guess1, winWord);
cout << done1 << "\n" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess2 = askInput(arr);
string done2 = buildResult(guess2, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess3 = askInput(arr);
string done3 = buildResult(guess3, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess4 = askInput(arr);
string done4 = buildResult(guess4, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << done4 << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess5 = askInput(arr);
string done5 = buildResult(guess5, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << done4 << endl;
cout << "_____" << endl;
string guess6 = askInput(arr);
string done6 = buildResult(guess6, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << done4 << endl;
cout << done5 << endl;
cout << done6 << endl;
}
int main() {
string wordArray[2315];
ifstream myfile ("proj1_data.txt");
cout << " Welcome to UMBC Wordle" << endl;
if (myfile.is_open())
{
string word;
int loop = 0;
while (getline(myfile, word))
{
wordArray[loop++] = word;
}
cout << " " << endl;
cout << " Your file was imported!" << endl;
cout << " 2315 Words imported" << endl;
cout << " " << endl;
myfile.close();
}
srand(time(0));
string chosenWord = wordArray[rand() % 2315];
playGame(chosenWord, wordArray);
return 0;
}
I dont get any errors when i compile it so i know that nothings "wrong" with the code, the problem is in the playGame function, i included the whole code in case that helps
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Link to Code: https://onlinegdb.com/B1DsFDa8D
Hello, my while loops aren't responding to their set conditions once the value is updated. the code just keeps going until it reaches the end. If you run the code you'll see what I'm talking about(in fact it is necessary that you do so). When the value of the parameter is updated the value does add up and changes. When I print out the value of it at the end of the code it does in fact register as the number that should be assigned to it throughout the loop but the loop just doesn't do anything when it should be stopped. Basically my problem might be an infinite loop. the only thing that counters it is a "return 0;" at the end of the loop.
My professor gave specific instructions: Create a hangman game. The game usually involves one player guessing letters to a secret word. Bad guesses cause the picture of a hangman to be drawn one segment at a time. Once there are 7 bad guesses, the hangman picture has been drawn and the player guessing loses the game. In your game, seven bad answers to any of 16 multiple choice questions will result in a lost game.
Program 1 Writes 16 questions to a file called “infile.txt”
Program 2 reads “infile.txt” and uses the questions for the hangman game
Use a boolean value-returning function called "is_hung". This function takes an integer parameter called "num_errors". This parameter is tested using an "if-else" statement to determine how much of the hangman to display to the screen based on the number of wrong answers.
The entire hangman can be displayed by the code segment below:
{
cout << "\t \t \t" << " O " << endl;
cout << "\t \t \t" << "/|\\" << endl;
cout << "\t \t \t" << " | " << endl;
cout << "\t \t \t" << "/ \\" << endl;
cout << " YOU ARE HUNG" endl;
return false;
}
1 incorrect answer displays the head
2 incorrect answers displays the left arm
3 incorrect answers displays the right arm
4 incorrect answers displays the top half of the body
5 incorrect answers displays the bottom half of the body
6 incorrect answers displays the left leg
7 incorrect answers displays the right leg
My Code:
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
bool is_hung(int, bool);
int main()
{
string question1;
string answer1;
string answer2;
string answer3;
string answer4;
string question2;
string answer5;
string answer6;
string answer7;
string answer8;
string question3;
string answer9;
string answer10;
string answer11;
string answer12;
string question4;
string answer13;
string answer14;
string answer15;
string answer16;
string question5;
string answer17;
string answer18;
string answer19;
string answer20;
string question6;
string answer21;
string answer22;
string answer23;
string answer24;
string question7;
string answer25;
string answer26;
string answer27;
string answer28;
string question8;
string answer29;
string answer30;
string answer31;
string answer32;
ifstream reader;
reader.open("infile.txt");
int num_right = 0;
int num_error = 0;
bool power = true;
cout << power << endl;
string user_answer1 = "";
string user_answer2 = "";
string user_answer3 = "";
string user_answer4 = "";
string user_answer5 = "";
string user_answer6 = "";
string user_answer7 = "";
string user_answer8 = "";
while (power == true) {
while (num_error < 7) //should stop the while loop when number of incorrect answers are equal to 7
{
//1
getline(reader, question1); //get line from infile.txt
getline(reader, answer1);
getline(reader, answer2);
getline(reader, answer3);
getline(reader, answer4);
cout << question1 << endl; //print out line from file
cout << answer1 << endl;
cout << answer2 << endl;
cout << answer3 << endl;
cout << answer4 << endl;
cout << "Enter Answer: ";
cin >> user_answer1; //have the user input answer
if (user_answer1 == "B") //if statement to determine correct answer
{
cout << "correct" << endl;
num_right++; //adds 1 to num_right
cout << "" << endl;
}
else //if user_answer is not equal answer/wrong answer
{
cout << "incorrect" << endl;
num_error++; //add 1 to num_error
power = is_hung(num_error, power); //get function
}
//2
getline(reader, question2);
getline(reader, answer5);
getline(reader, answer6);
getline(reader, answer7);
getline(reader, answer8);
cout << question2 << endl;
cout << answer5 << endl;
cout << answer6 << endl;
cout << answer7 << endl;
cout << answer8 << endl;
cout << "Enter Answer: ";
cin >> user_answer2;
if (user_answer2 == "B") {
cout << "correct" << endl;
num_right++;
cout << "" << endl;
}
else {
cout << "incorrect" << endl;
num_error++;
power = is_hung(num_error, power);
}
//3
getline(reader, question3);
getline(reader, answer9);
getline(reader, answer10);
getline(reader, answer11);
getline(reader, answer12);
cout << question3 << endl;
cout << answer9 << endl;
cout << answer10 << endl;
cout << answer11 << endl;
cout << answer12 << endl;
cout << "Enter Answer: ";
cin >> user_answer3;
if (user_answer3 == "C") {
cout << "correct" << endl;
num_right++;
cout << "" << endl;
}
else {
cout << "incorrect" << endl;
num_error++;
power = is_hung(num_error, power);
}
//4
getline(reader, question4);
getline(reader, answer13);
getline(reader, answer14);
getline(reader, answer15);
getline(reader, answer16);
cout << question4 << endl;
cout << answer13 << endl;
cout << answer14 << endl;
cout << answer15 << endl;
cout << answer16 << endl;
cout << "Enter Answer: ";
cin >> user_answer4;
if (user_answer4 == "D") {
cout << "correct" << endl;
num_right++;
cout << "" << endl;
}
else {
cout << "incorrect" << endl;
num_error++;
power = is_hung(num_error, power);
}
//5
getline(reader, question5);
getline(reader, answer17);
getline(reader, answer18);
getline(reader, answer19);
getline(reader, answer20);
cout << question5 << endl;
cout << answer17 << endl;
cout << answer18 << endl;
cout << answer19 << endl;
cout << answer20 << endl;
cout << "Enter Answer: ";
cin >> user_answer5;
if (user_answer5 == "A") {
cout << "correct" << endl;
num_right++;
cout << "" << endl;
}
else {
cout << "incorrect" << endl;
num_error++;
power = is_hung(num_error, power);
}
//6
getline(reader, question6);
getline(reader, answer21);
getline(reader, answer22);
getline(reader, answer23);
getline(reader, answer24);
cout << question6 << endl;
cout << answer21 << endl;
cout << answer22 << endl;
cout << answer23 << endl;
cout << answer24 << endl;
cout << "Enter Answer: ";
cin >> user_answer6;
if (user_answer6 == "D") {
cout << "correct" << endl;
num_right++;
cout << "" << endl;
}
else {
cout << "incorrect" << endl;
num_error++;
power = is_hung(num_error, power);
}
//7
getline(reader, question7);
getline(reader, answer25);
getline(reader, answer26);
getline(reader, answer27);
getline(reader, answer28);
cout << question7 << endl;
cout << answer25 << endl;
cout << answer26 << endl;
cout << answer27 << endl;
cout << answer28 << endl;
cout << "Enter Answer: ";
cin >> user_answer7;
if (user_answer7 == "A") {
cout << "correct" << endl;
num_right++;
cout << "" << endl;
}
else {
cout << "incorrect" << endl;
num_error++;
power = is_hung(num_error, power);
}
cout << power << endl;
//8
getline(reader, question8);
getline(reader, answer29);
getline(reader, answer30);
getline(reader, answer31);
getline(reader, answer32);
cout << question8 << endl;
cout << answer29 << endl;
cout << answer30 << endl;
cout << answer31 << endl;
cout << answer32 << endl;
cout << "Enter Answer: ";
cin >> user_answer8;
if (user_answer8 == "D") {
cout << "correct" << endl;
num_right++;
cout << "" << endl;
}
else {
cout << "incorrect" << endl;
num_error++;
power = is_hung(num_error, power);
}
cout << "" << endl;
if (num_error > 7) {
cout << "You got " << num_right << " out of 8. You lose." << endl;
}
else if (num_error < 7) {
cout << "You got " << num_right << " out of 8. You Win." << endl;
}
reader.close();
return 0;
}
}
reader.close();
cout << "" << endl;
if (num_error > 7) {
cout << "You got " << num_right << " out of 16. You lose." << endl;
}
else if (num_error < 7) {
cout << "You got " << num_right << " out of 16. You Win." << endl;
}
return 0;
}
bool is_hung(int num_errors2, bool power2)
{
if (num_errors2 == 1) {
cout << "\t \t \t"
<< " O " << endl;
cout << "" << endl;
power2 = true;
return power2;
}
else if (num_errors2 == 2) {
cout << "\t \t \t"
<< " O " << endl;
cout << "\t \t \t"
<< "/" << endl;
cout << "" << endl;
power2 = true;
return power2;
}
else if (num_errors2 == 3) {
cout << "\t \t \t"
<< " O " << endl;
cout << "\t \t \t"
<< "/ \\" << endl;
cout << "" << endl;
power2 = true;
return power2;
}
else if (num_errors2 == 4) {
cout << "\t \t \t"
<< " O " << endl;
cout << "\t \t \t"
<< "/|\\" << endl;
cout << "" << endl;
power2 = true;
return power2;
}
else if (num_errors2 == 5) {
cout << "\t \t \t"
<< " O " << endl;
cout << "\t \t \t"
<< "/|\\" << endl;
cout << "\t \t \t"
<< " | " << endl;
cout << "" << endl;
power2 = true;
return power2;
}
else if (num_errors2 == 6) {
cout << "\t \t \t"
<< " O " << endl;
cout << "\t \t \t"
<< "/|\\" << endl;
cout << "\t \t \t"
<< " | " << endl;
cout << "\t \t \t"
<< "/ " << endl;
cout << "" << endl;
power2 = true;
return power2;
}
else if (num_errors2 == 7) {
cout << "\t \t \t"
<< " O " << endl;
cout << "\t \t \t"
<< "/|\\" << endl;
cout << "\t \t \t"
<< " | " << endl;
cout << "\t \t \t"
<< "/ \\" << endl;
cout << " YOU ARE HUNG" << endl;
cout << "" << endl;
power2 = false;
return power2;
}
}
There is a ridiculous amount of wasteful, repetitive code, which makes it extremely difficult to read and debug, and significantly increases the risk of making mistakes.
This code can be greatly reduced by making use of fewer variables, better loops, and a little arithmetic, eg:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool is_hung(int);
int main()
{
string question;
string answer;
string user_answer;
const string correct_answers = “BBCDADADBDABCABB”;
int num_right = 0;
int num_error = 0;
ifstream reader("infile.txt");
for(int i = 0; i < 16; ++i)
{
getline(reader, question); // get line from infile.txt
cout << question << endl; // print out line from file
for (int j = 0; j < 4; ++j)
{
getline(reader, answer);
cout << answer << endl;
}
cout << "Enter Answer: ";
cin >> user_answer; // have the user input answer
if (user_answer == correct_answers[i]) // if statement to determine correct answer
{
cout << "correct" << endl;
num_right++; // adds 1 to num_right
cout << endl;
}
else // if user_answer is not equal answer/wrong answer
{
cout << "incorrect" << endl;
num_error++; // add 1 to num_error
if (is_hung(num_error)) // get function
break;
}
}
reader.close();
cout << endl;
if (num_error == 7)
{
cout << "You got " << num_right << " out of 16. You lose." << endl;
}
else
{
cout << "You got " << num_right << " out of 16. You Win." << endl;
}
return 0;
}
bool is_hung(int num_errors)
{
cout << "\t \t \t" << " O ";
if (num_errors >= 2)
{
cout << endl;
cout << "\t \t \t" << "/";
}
if (num_errors >= 3)
{
cout << (num_errors >= 4 ? ‘|’ : ‘ ‘) << “\\”;
}
if (num_errors >= 5)
{
cout << endl;
cout << "\t \t \t" << " | ";
}
if (num_errors >= 6)
{
cout << endl;
cout << "\t \t \t" << "/";
}
if (num_errors >= 7)
{
cout << " \\" << endl;
cout << " YOU ARE HUNG";
}
cout << endl;
return (num_errors < 7);
}
Don’t you think that is much easier to work with?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct football_game
{
string visit_team;
int home_score;
int visit_score;
};
void printMenu();
int main()
{
int i, totalValues = 0;
ifstream inputFile;
string temp = "";
inputFile.open("games.txt");
if (!inputFile)
{
cout << "Error opening Input file!" << endl;
exit(101);
}
inputFile >> totalValues;
getline(inputFile, temp);
cout << " *** Football Game Scores *** " << endl << endl;
cout << " * Total Number of teams : " << totalValues << endl << endl;
football_game* records = new football_game[totalValues];
// while (!inputFile.eof())
// {// == NULL) {
for (i = 0; i < totalValues; i++)
{
getline(inputFile, records[i].visit_team);
cout << records[i].visit_team << endl;
inputFile >> records[i].home_score >> records[i].visit_score;
cout << records[i].home_score << " " << records[i].visit_score << endl;
getline(inputFile, temp);
}
//}
cout << endl;
int choice = 0;
int avg_home_Score = 0;
int avg_visit_Score = 0;
printMenu(); // prints menu
cout << "Please Enter a choice from the Menu : ";
cin >> choice;
cout << endl << endl;
while (true)
{
switch (choice)
{
case 1:
cout << " Score Table " << endl;
cout << " ***********************" << endl << endl;
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
for (int i = 0; i < totalValues; i++)
{
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|' << setw(7)
<< right << records[i].visit_score << " " << '|' << endl;
}
cout << endl << endl << endl;
break;
case 2:
{
string team_name;
cout << "Enter the Team Name : ";
cin >> team_name;
for (int i = 0; i < totalValues; i++)
{
if (records[i].visit_team == team_name)
{
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|'
<< setw(7) << right << records[i].visit_score << " " << '|'
<< endl;
}
}
cout << endl;
break;
}
case 3:
{
for (int i = 0; i < totalValues; i++)
avg_home_Score += records[i].home_score;
cout << "Average home_score: " << (avg_home_Score / totalValues) << endl << endl;
break;
}
case 4:
{
for (int i = 0; i < totalValues; i++)
avg_visit_Score += records[i].visit_score;
cout << "Average visit_score: " << (avg_visit_Score / totalValues) << endl << endl;
break;
}
default:
{
cout << "Please enter valid input !!" << endl;
break;
}
}
printMenu();
cin >> choice;
}
return 0;
}
void printMenu()
{
cout << " Menu Options " << endl;
cout << " ================ " << endl;
cout << " 1. Print Information of all Games[Table Form] " << endl;
cout << " 2. Print Information of a Specific Game " << endl;
cout << " 3. Print Average points scored by the Home Team during season" << endl;
cout << " 4. Print Average points scored against the Home Team" << endl << endl << endl;
}
Here is the input file i am using
games.txt
5
SD Mines
21 17
Northern State
10 3
BYU
10 21
Creighton
14 7
Sam Houston State
14 24
When i am using the 2nd option (Print Information of a Specific Game) from the output screen,
it ask me to enter the team name and when i enter the team-name.
For example: SD Mines it gives me an error, but when I enter the team-name with no space like: BYU it works fine for me.
cin >> team_name;
Takes the input only upto space.
You might want to use cin.getline() for taking space separated strings as input.
A small program demonstrating the same :
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Name is : , " << name << "!\n";
return 0;
}
std::cin ignores whitespaces by default.
To include spaces in your input try :
getline(cin, team_name);
This would pick up all the characters in a line until you press enter. This is available in
#include<string>
You need to flush the std::cin buffer after reading the choice:
#include <limits>
//...
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Refer to this question for detailed explanation.
Also, if you want to read strings with spaces from the standard input, replace this:
cin >> team_name;
with this:
getline(cin, team_name);
as already mentioned in other answers. No need to flush std::cin this time, since you have already read the full line.
Finally, remove extra newlines from your games.txt:
5
SD Mines
21 17
Northern State
...
I am trying to do a hangman project, but my code isn't working. Whenever I put in the proper letter, the code tells me it is wrong (even though it is right). Not really sure why - the code worked at some point but I changed some things and now I don't know why it doesn't work. So it is probably a simple fix, but I am just not seeing it.
Any help would be very appreciated!
#include <iostream>
using namespace std;
int letterFill (char, string, string&);
int main()
{
string name;
int maxAttempts = 5;
int wrongGuesses;
char letter;
srand(time(0));
const string wordList[15] = { "hanukkah", "sparklers", "mistletoe", "menorah", "presents", "reindeer",
"kwanzaa", "snowman", "eggnog", "celebration", "yuletide", "resolution", "nutcracker", "ornaments", "gingerbread" };
string correctWord = wordList[rand() % 15];
string unknown(correctWord.length(),'*');
cout << correctWord << endl;
cout << "Welcome to a fun game of winter holiday hangman! What is your name? " << endl;
cin >> name;
cout << name <<", there are some simple things you should know about this game before you start playing!" << endl;
cout << "You will be trying to guess a randomly selected word by typing in ONE letter at a time " << endl;
cout << "You will have " << maxAttempts << " tries before losing the game " << endl;
cout << "And remember, all of the words are winter holiday related. Good luck " << name <<"!" << endl;
cout << "*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*" <<endl;
while (wrongGuesses == 0)
{
cout << "Guess a letter" << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 1)
{
cout << "You have 4 guesses left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 2)
{
cout << "You have 3 guesses left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 3)
{
cout << "You have 2 guesses left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 4)
{
cout << "You have 1 guess left " << endl;
cout << "Guess a letter " << cout;
cin >> letter;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
while (wrongGuesses == 5)
{
cout << "Sorry " << name << " you have made 5 wrong guesses!" << endl;
cout << "Game over. Click any key to exit. Play again soon :) " << endl;
if (letterFill(letter, correctWord, unknown)==0)
{
cout << endl << "That letter is not in this word! Try again " << endl;
wrongGuesses = wrongGuesses + 1;
}
else
{
cout << endl << "You found a letter! Keep up the good work! " << endl;
}
if (correctWord==unknown)
{
cout << correctWord << endl;
cout << "Congratulations! You guessed the correct word!" << endl;
}
}
system("pause");
return 0;
}
int letterFill (char guessLetter, string mysteryWord, string& guessWord)
{
int x;
int matches=0;
int lengthWord=mysteryWord.length();
for (x = 0; x< lengthWord; x++)
{
if (guessLetter == mysteryWord[x])
return 0;
if (guessLetter == mysteryWord[x])
{
guessWord[x] = guessLetter;
matches++;
}
}
return matches;
}
You aren't updating the string guessWord in your int letterFill() function. As soon as you see a letter that matches you return without entering that second if statement.
I assume what you want is only to return after fully updating the guessWord, based on that what you want to do is iterate through the string, updating guessWord as you find matches and after your loop do a check
if(matches == 0) return 0;
else return matches;
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.