c++ variable output unexpected - c++

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

Related

How to access class object from a function

Ok So I have abit of a problem with my code that I cant seem to find the solution for. Im writing a program that will work like a phonebook for your phone. And everything that happens will be saved in a .txt file. So when the program starts it will always read from the same file and put that into class objects called "person" and then you will be able to edit/delete/add new contacts and then it gets rewriten to the file.
The problem im having right now is that I want to make more of the code into functions instead of having it all in the main folder. So as you can see from the two last functions, one should read from the file and the other should write to the file. What I want to do is to replace all the code in main() that has to do with readToFile and writeToFile. Also i would like to be able to put the writeToFile function after every case switch action like edit/delete/add. So that you dont have to choose to write to the file. It just does that automatically.
Can I somehow use pointers/references for this or how do i get access to the "person" objects in my functions.
First time asking a question here so feel free to educate me if i did something wrong.
Here is the code:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
void printline(char, int);
bool name_valid(string);
class contact
{
public:
string fName, lName, adress, epost, mobileNo, birthday;
//initialize the contact by a default value
contact() : fName(""), lName(""), adress(""), epost(""), mobileNo(""), birthday("")
{}
// Write all contacts to the file.
bool writeToFile()
{
if (fName != "")
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1; //Success!!
}
else
{
cout << " Fail!" << endl;
return 0; //Fail!!
}
}
//Show all contacts
bool showAll()
{
if (fName != "")
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1; //Success!!
}
else
return 0; //Fail!!
}
// Search
bool Search(string search_word)
{
if (search_word == fName)
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1;
}
else
return 0;
}
// Check if a name exists or not
bool name_exists(string tname)
{
if (tname == fName)
return 1;
else
return 0;
}
// The contact object is initialized by valid values
bool addContact(string new_fName, string new_lName, string new_adress, string new_epost, string new_mobileNo, string new_birthday )
{
if (fName == "")
{
fName = new_fName;
lName = new_lName;
adress = new_adress;
epost = new_epost;
mobileNo = new_mobileNo;
birthday = new_birthday;
return 1; // Success !!
}
else
return 0; // Failure !!
}
//edits the contact details
bool edit(string);
bool erase(string new_name)
{
if (new_name == fName)
{
fName = "";
lName = "";
adress = "";
epost = "";
mobileNo = "";
birthday = "";
return 1;
}
else
return 0;
}
};
// Edits the contact
bool contact::edit(string name_check)
{
string new_fName, new_lName, new_adress, new_epost, new_mobileNo, new_birthday;
if (name_check == fName)
{
cin.ignore();
cin.clear();
cout << "Enter new first name: ";
getline(cin,new_fName);
cout << "Enter new lastname: ";
getline(cin,new_lName);
cout << "Enter new adress: ";
getline(cin,new_adress);
cout << "Enter new epost: ";
getline(cin,new_epost);
cout << "Enter new birthday: ";
getline(cin,new_birthday);
fName = new_fName;
lName = new_lName;
adress = new_adress;
epost = new_epost;
birthday = new_birthday;
return 1;
}
else
return 0;
}
int main()
{
contact person[100];
ifstream infile("Phonebook.txt");
string temp_fName, temp_lName, temp_adress, temp_epost, temp_mobilNo, temp_birthday;
int counter, choice, i;
bool flag;
bool cancel_flag;
// Read from file to contact person
string ignoreName, ignoreCell, ignoreAdress, ignoreEmail, ignoreBirthday;
string fileFirstname, fileLastname, fileCell, fileAdress, fileEmail, fileBirthday;
// Goes through the text file and put all the names in the contact class
while (!infile.eof())
{
getline(infile, ignoreName, ' ');
getline(infile, fileFirstname, ' ');
getline(infile, fileLastname);
getline(infile, ignoreCell, ' ');
getline(infile, fileCell);
getline(infile, ignoreAdress, ' ');
getline(infile, fileAdress);
getline(infile, ignoreEmail, ' ');
getline(infile, fileEmail);
getline(infile, ignoreBirthday, ' ');
getline(infile, fileBirthday);
// Check if the file is empty
if (!infile)
{
break;
}
for (i = 0; i < 100; i++)
if (person[i].addContact(fileFirstname, fileLastname, fileAdress, fileEmail, fileCell, fileBirthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
}
infile.close();
ofstream outfile("Phonebook.txt");
cout << "=========== Your Phonebook ==========" << endl;
do
{
cout << "\n\n";
printline('-', 25);
cout << "1. Add Contact" << endl
<< "2. Edit Contact" << endl
<< "3. Delete Contact" << endl
<< "4. Search" << endl
<< "5. Show All Contacts" << endl
<< "6. Write All Contacts To File." << endl
<< "0. Exit" << endl << endl
<< "Your choice... ";
cin >> choice;
system("cls");
printline('-', 20);
cancel_flag = 0;
flag = 0;
counter = 0;
switch (choice)
{
case 0:
return 0;
break;
// Adds a new contact
case 1:
cout << "Add New Contact\t\t\t\tpress - to cancel" << endl;
printline('-', 25);
counter = 0;
// Loop until correct contact info is untered
do
{
flag = 0;
if (counter)
cout << "Try again \t\t\t\tpress - to cancel" << endl;
//count how many times the do-while loop executes
counter++;
cin.ignore();
cin.clear();
cout << "First Name: ";
getline(cin, temp_fName);
cout << "Last Name: ";
getline(cin, temp_lName);
cout << "Adress: ";
getline(cin, temp_adress);
cout << "Email: ";
getline(cin, temp_epost);
cout << "Mobile Number: ";
getline(cin, temp_mobilNo);
cout << "Birthday: ";
getline(cin, temp_birthday);
if (temp_fName == "-")
{
cancel_flag = 1;
break;
}
for (i = 0; i < 100; i++)
{
if (person[i].name_exists(temp_fName))
{
cout << "The name you entered is already there"
"in the phonebook, entere a different name." << endl;
flag = 1;
break;
}
}
} while (!name_valid(temp_fName) || flag);
if (cancel_flag)
{
system("cls");
break;
}
//This loop adds the contact to the phonebook
for (i = 0; i < 100; i++)
if(person[i].addContact(temp_fName, temp_lName, temp_adress, temp_epost, temp_mobilNo, temp_birthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
if (!flag)
cout << "Memory full! Delete some contacts first." << endl;
break;
// Edits an existing contact
case 2:
cout << "Enter a contact name to edit \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
for (i = 0; i < 100; i++)
if (person[i].edit(temp_fName))
{
cout << "Edited Successfully!" << endl;
flag = 1;
break;
}
if (!flag)
cout << "Contact name not found!" << endl;
break;
//Delete a contact
case 3:
do
{
if (counter)
cout << "Try again" << endl;
counter++;
cout << "Enter a contact name to delete: \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
//Final Confirmation
for (i = 0; i < 100; i++)
if (person[i].name_exists(temp_fName))
{
flag = 1;
cout << "Are you sure you want to delete (1/0)" << endl;
int yes;
cin >> yes;
if (!yes)
{
system("cls");
cancel_flag = 1;
}
break;
}
if (!flag)
cout << "Contact name not found!" << endl;
if (cancel_flag)
break;
// This code deletes the contact
if (flag)
{
for (i = 0; i < 100; i++)
if (person[i].erase(temp_fName))
{
cout << "Deleted successfully!" << endl;
break;
}
}
} while (!flag);
break;
// Search a contact
case 4:
do
{
if (counter)
cout << "Try again" << endl;
counter++;
cout << "Search a name: \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
for (i = 0; i < 100; i++)
if (person[i].Search(temp_fName))
{
flag = 1;
break;
}
if (!flag)
cout << "Contact namew not found!" << endl;
} while (!flag);
break;
// Show all the contacts
case 5:
cout << "Showing Contacts" << endl;
printline('-', 25);
for (i = 0; i < 100; i++)
{
if (person[i].showAll())
{
flag = 1;
cout << "\n\n";
}
}
if (!flag)
cout << "No contacts found!" << endl;
break;
case 6:
// Write to file
cout << "Writing to file." << endl;
printline('-', 25);
for (int i = 0; i < 100; i++)
{
if (person[i].fName != "")
{
outfile << "Name: " << person[i].fName << " " << person[i].lName << "\n" << "Mobilenumber: " << person[i].mobileNo << "\n" << "Adress: " << person[i].adress << "\n" << "Email: " << person[i].epost << "\n" << "Birthday: " << person[i].birthday << "\n\n\n\n";
flag = 1;
cout << "\n\n";
}
}
break;
}
}while (1);
return 0;
}
//prints a line
void printline(char ch, int size)
{
for (int i = 0; i < size; i++)
cout << ch;
cout << "\n";
}
//Contact name validation
bool name_valid(string tname)
{
if (tname.size() > 20)
{
cout << "Invalid name!\nEnter a name within 20 characters!" << endl;
return 0;
}
else if (tname == "")
{
cout << "Invalid Name!\nName cannot be blank" << endl;
return 0;
}
else
return 1;
}
void writeToFile()
{
cout << "Writing to file." << endl;
printline('-', 25);
for (int i = 0; i < 100; i++)
{
if (person[i].fName != "")
{
outfile << "Name: " << person[i].fName << " " << person[i].lName << "\n" << "Mobilenumber: " << person[i].mobileNo << "\n" << "Adress: " << person[i].adress << "\n" << "Email: " << person[i].epost << "\n" << "Birthday: " << person[i].birthday << "\n\n\n\n";
flag = 1;
cout << "\n\n";
}
}
}
void readfromfile()
{
ifstream infile("Phonebook.txt");
string ignoreName, ignoreCell, ignoreAdress, ignoreEmail, ignoreBirthday;
string fileFirstname, fileLastname, fileCell, fileAdress, fileEmail, fileBirthday;
// Goes through the text file and put all the names in the contact class
while (!infile.eof())
{
getline(infile, ignoreName, ' ');
getline(infile, fileFirstname, ' ');
getline(infile, fileLastname);
getline(infile, ignoreCell, ' ');
getline(infile, fileCell);
getline(infile, ignoreAdress, ' ');
getline(infile, fileAdress);
getline(infile, ignoreEmail, ' ');
getline(infile, fileEmail);
getline(infile, ignoreBirthday, ' ');
getline(infile, fileBirthday);
// Check if the file is empty
if (!infile)
{
break;
}
for (int i = 0; i < 100; i++)
if (person[i].addContact(fileFirstname, fileLastname, fileAdress, fileEmail, fileCell, fileBirthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
}
infile.close();
}
Just pass in an array to the function (and others which are needed). Now the size of the array is known beforehand so we can protect it from array decay too. It'll look something like this,
void writeToFile(contact(&person)[100], std::fstream& outfile, bool& flag) { ... }
void readfromfile(contact(&person)[100], bool& flag) { ... }
Note that were passing in the others (flag and outfile) using the reference so that the actual variable can be altered.
From the two, I would recommend using the second option. Its clean, simple and safe (if you may).
Note: Try not to use using namespace std;. It not a good practice and basically your taking the std namespace and putting it in the global namespace. Now that namespace is huuuuggeeeeee. Later to access its objects and stuff, use :: operator.

C++ Strings getting printed as hex, when that isnt the purpose

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

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 [closed]

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?

How to move back and forth in array list C++?

So I want to search my array for my data and move back and forth, so this is what i came up with, however this isn't working, can there be a better way to do this ? I tried to google some tips however I wasn't finding a suitable way to do this...
Can binary search be used to do this same thing ?
struct student
{
int stid = NULL;
char stname[15] = "NULL";
int grades = NULL;
string date = NULL;
};
int main()
{
int choose = 0;
int stid = 0;
int array = 1;
struct student s[1] = { 001, "Sara", "123456", "Canada", "02/01/2019" };
while (choose != 4)
{
cout << "1. Add\n";
cout << "2. View\n";
cout << "3. Search\n";
cout << "4. Quit\n";
cin >> choose;
if (choose == 3)
{
cout << "How would you like to find the Student Details?" << endl;
cout << "1 - By student id " << endl;
int choice = 0;
cin >> choice;
if (choice == 1)
{
cout << "Student ID: ";
cin >> stid;
for (int i = 0; i < array; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
while (true)
{
cout << "Which record do you wish to see?" << endl;
cout << " 1 : Forth " << endl;
cout << " 2 : Back " << endl;
int choice = 0;
cin >> choice;
if (choice == 1)
{
stid = stid + 1;
for (int i = 0; i == stid; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
}
}
}
else if (choice == 2)
{
stid = stid - 1;
for (int i = 0; i == stid; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
}
}
}
Thank you for helping.

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.