C++ Hangman Code won't work correctly - c++

my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
int instructions();
void manual();
void file(char*);
int letterFill(char, char*, char*);
void Unknown(char*, char*);
const int MAX_LENGTH = 10;
void main()
{
bool done = false;
char word[MAX_LENGTH];
char unknown[MAX_LENGTH];
char letter;
char name[MAX_LENGTH];
int wrong_guesses = 0;
int MAX_TRIES;
char ans;
while (!done)
{
switch (instructions())
{
case 1:
{
manual();
break;
}
case 2:
{
file(word);
break;
}
}
cout << "WHAT IS THE NUMBER OF GUESSES ALLOWED?: " << endl;
cin >> MAX_TRIES;
Unknown(word, unknown);
cout << endl << endl << "HANGMAN";
cout << endl << endl << "Each letter is represented by a star." << endl;
cout << "You have " << MAX_TRIES << " tries left.";
cout << "ENTER GUESS WHEN READY: ";
cin >> letter;
while (letter != 'N' && letter != 'n')
{
while (wrong_guesses < MAX_TRIES)
{
cout << unknown << endl;
cout << "Guess a letter: " << flush;
cin >> letter;
if (letterFill(letter, word, unknown) == 0)
{
cout << endl << "You got it wrong! You lose a guess" << endl;
wrong_guesses++;
}
else
{
cout << endl << "Pfft, you got lucky" << endl;
}
cout << "Guesses Left: " << MAX_TRIES - wrong_guesses << endl;
if (strcmp(word, unknown) == 0)
{
cout << word << endl;
cout << "You got it!" << endl;
exit(0);
}
cout << "You've been hanged." << endl;
cout << "The word was : " << word << endl;
}
}
cout << "Try again? (y/n): " << flush;
cin >> ans;
if (ans == 'y' || ans == 'Y')
done = true;
else
done = false;
}
system("pause");
}
int instructions()
{
int select = 0;
cout << endl << "HANGMAN" << endl << endl;
cout << " PROGRAM MENU" << endl;
cout << " Select option 1 or 2" << endl << endl;
cout << " 1. INPUT WORD MANUALLY" << endl;
cout << " 2. PLAY AGAINST THE COMPUTER" << endl;
cout << " 3. EXIT PROGRAM BY INPUTING: N or n" << endl << endl;
cin >> select;
return select;
}
void manual()
{
string word;
cout << endl << "INPUT WORD: " << endl;
cin >> word;
return;
}
void file(char *roc)
{
ifstream fin("word.txt");
int x;
int count = 1;
int word;
int i = 0;
srand(time(0));
word = rand() % 20;
while (count < word)
{
fin >> x;
if (x == 0)
{
count++;
}
}
do
{
fin >> x;
roc[i++] = char(x);
} while (x);
return;
}
int letterFill(char guess, char *secretword, char *guessword)
{
int i;
int matches = 0;
for (i = 0; i<MAX_LENGTH; i++)
{
if (secretword[i] == 0)
{
break;
}
if (guess == guessword[i])
{
return 0;
}
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
void Unknown(char *word, char *unknown)
{
int i;
int length = strlen(word);
for (i = 0; i<length; i++)
{
unknown[i] = '*';
}
unknown[i] = 0;
}
Again
my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.

Related

Error: expected primary-expression before ']' token. Need assitance with function definition and calling

This is my first semester of computer science, and I need help with my first project. So far, it's still a mess, and I am mainly doing test cases to ensure basic things like my functions work.
The goal of the project is to ask the user how many robots they want to make, name them, then they can use the robot's name (their unique identifier) to move the robots along an X-Y axis, which is really just the program adding or subtracting to a .Xvalue or .Yvalue.
My MenuFunction works, but I am having trouble with the MoveFunction. Basically, I want the MoveFunction to ask the user which robot they want to use, go through the RobotArray, and print the Robot's name once found.
Again, this is just a test case so I can better understand the coding. Right now, I am getting two errors:
main.cpp:42:33: error: expected primary-expression before ‘]’ token
42 | string MoveFunction(RobotArray[], robotName, NumberOfRobots);
main.cpp:62:16: error: no match for call to ‘(std::string {aka std::__cxx11::basic_string}) ()’
62 | MoveFunction();
I don't know what to do for the first error, but I think the latter is due to my not having any objects in the function call, but I wouldn't know what to put in there anyway.
My complete code is below:
#include <iostream>
using namespace std;
struct userRobot
{
string name;
int Xvalue = 0;
int Yvalue = 0;
};
void MenuFunction()
{
cout << "Welcome to MultiRobo Guider." << endl;
cout << "Please select:" << endl;
cout << "m - move" << endl << "d - distance" << endl << "q - quit" << endl << endl;
}
int main()
{
int NumberOfRobots;
string robotName;
cout << "Enter the number of robots" << endl;
cin >> NumberOfRobots;
cout << endl << "Enter their name(s)" << endl;
userRobot RobotArray[NumberOfRobots];
for (int i = 0; i < NumberOfRobots; i++)
{
cin >> robotName;
RobotArray[i].name = robotName;
}
cout << endl;
for (int j = 0; j < NumberOfRobots; j++)
{
cout << RobotArray[j].name << "'s position is ";
cout << "(" << RobotArray[j].Xvalue << "," << RobotArray[j].Yvalue << ")" << endl << endl;
}
string MoveFunction(RobotArray[], robotName, NumberOfRobots);
{
cin >> robotName;
for (int k = 0; k < NumberOfRobots; k++)
{
if (robotName == RobotArray[k].name)
{
cout << RobotArray[k].name;
}
}
}
MenuFunction();
char input;
cin >> input;
if (input == 'm')
{
cout << "Which robot would you like to move?";
MoveFunction();
}
else if (input == 'd')
{
cout << "distance";
}
else if (input == 'q')
{
cout << "quit";
}
}
First off, userRobot RobotArray[NumberOfRobots]; is a variable-length array, which is a non-standard extension supported by only a few compilers. To create an array whose size is not known until runtime, you should use new[] instead, or better std::vector.
That said, your main issue is that you are trying to define your MoveFunction() function inside of your main() function, which is not allowed. But, even if it were, you are not declaring it correctly. It has an erroneous ; on it. And RobotArray, robotName, and NumberOfRobots are not types, but variables. Like a variable, a function parameter always starts with a type. There are no untyped parameters/variables in C++.
You need to either:
move MoveFunction() outside of main(), and fix its declaration to use proper types, eg:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct userRobot
{
string name;
int Xvalue = 0;
int Yvalue = 0;
};
void MenuFunction()
{
cout << "Welcome to MultiRobo Guider." << endl;
cout << "Please select:" << endl;
cout << "m - move" << endl << "d - distance" << endl << "q - quit" << endl << endl;
}
void MoveFunction(userRobot RobotArray[], int NumberOfRobots)
{
cout << "Which robot would you like to move?";
string robotName;
cin >> robotName;
for (int k = 0; k < NumberOfRobots; k++)
{
if (robotName == RobotArray[k].name)
{
cout << RobotArray[k].name << endl;
return;
}
}
cout "Robot not found" << endl;
}
int main()
{
cout << "Enter the number of robots" << endl;
int NumberOfRobots;
cin >> NumberOfRobots;
vector<userRobot> RobotArray(NumberOfRobots);
cout << endl << "Enter their name(s)" << endl;
for (int i = 0; i < NumberOfRobots; i++)
{
cin >> RobotArray[i].name;
}
cout << endl;
for (int j = 0; j < NumberOfRobots; j++)
{
cout << RobotArray[j].name << "'s position is ";
cout << "(" << RobotArray[j].Xvalue << "," << RobotArray[j].Yvalue << ")" << endl << endl;
}
MenuFunction();
char input;
cin >> input;
if (input == 'm')
{
MoveFunction(RobotArray.data(), NumberOfRobots);
}
else if (input == 'd')
{
cout << "distance";
}
else if (input == 'q')
{
cout << "quit";
}
}
or change MoveFunction() into a lambda, eg:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct userRobot
{
string name;
int Xvalue = 0;
int Yvalue = 0;
};
void MenuFunction()
{
cout << "Welcome to MultiRobo Guider." << endl;
cout << "Please select:" << endl;
cout << "m - move" << endl << "d - distance" << endl << "q - quit" << endl << endl;
}
int main()
{
cout << "Enter the number of robots" << endl;
int NumberOfRobots;
cin >> NumberOfRobots;
vector<userRobot> RobotArray(NumberOfRobots);
cout << endl << "Enter their name(s)" << endl;
for (int i = 0; i < NumberOfRobots; i++)
{
cin >> RobotArray[i].name;
}
cout << endl;
for (int j = 0; j < NumberOfRobots; j++)
{
cout << RobotArray[j].name << "'s position is ";
cout << "(" << RobotArray[j].Xvalue << "," << RobotArray[j].Yvalue << ")" << endl << endl;
}
auto MoveFunction = [&]{
cout << "Which robot would you like to move?";
string robotName;
cin >> robotName;
for (int k = 0; k < NumberOfRobots; k++)
{
if (robotName == RobotArray[k].name)
{
cout << RobotArray[k].name << endl;
return;
}
}
cout "Robot not found" << endl;
};
MenuFunction();
char input;
cin >> input;
if (input == 'm')
{
MoveFunction();
}
else if (input == 'd')
{
cout << "distance";
}
else if (input == 'q')
{
cout << "quit";
}
}
You have a semi-colon at the end of MoveFunction() definition, In C++ when you define a function the name of the function does not end with a semi-colon.

Display Array User Input from Function

This is my code at the moment. It is a lottery game and I get user input for 7 numbers and do not allow duplicates (same goes with the random generated). I need to display the user's numbers and the winning random numbers at the end of the main next to LOTTO RESULTS and WINNING NUMBERS.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void getLottoPicks(int userNums[], int size);
void genWinNums(int winNums[], int size);
int main()
{
const int size = 7;
int UserTicket[size];
int WinningNums[size];
char selection;
string name;
do
{
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "q) Quit Program" << endl;
cout << "Please make a selection : " << endl;
cin >> selection;
if (selection == '1')
{
cout << "Please enter your name: " << endl;
cin.ignore();
getline(cin, name);
getLottoPicks(UserTicket, size);
genWinNums(WinningNums, size);
cout << name << "'s LOTTO RESULTS" << endl;
cout << "----------------------" << endl;
cout << "WINNING TICKET NUMBERS : " << endl;
cout << name << "'s TICKET : " << endl;
}
else if (selection == 'q')
{
cout << "You have chosen to quit the program. Thank you for using!" << endl;
}
else
{
cout << "Invalid selection. Please try again." << endl;
}
} while (selection != 'q');
return 0;
}
void getLottoPicks(int userNums[], int size)
{
for (int times = 0; times < size; times++)
{
int input;
cout << "selection #" << times + 1 << ": " << endl;
cin >> input;
bool isNotDuplicate = true;
for (int i = 0; i < times; i++)
{
if (userNums[i] == input)
{
isNotDuplicate = false;
}
}
if (isNotDuplicate == true)
{
userNums[times] = input;
}
else
{
cout << "You already picked this number. Please enter a different number: " <<
endl;
times--;
}
}
}
void genWinNums(int winNums[], int size)
{
srand((unsigned int)time(NULL));
for (int times = 0; times < size; times++)
{
int i;
bool isNotDuplicate = true;
while (isNotDuplicate)
{
isNotDuplicate = false;
i = 1 + rand() % 40;
for (int j = 0; j < times; j++)
{
if (i == winNums[j])
{
isNotDuplicate = true;
}
}
}
winNums[times] = i;
}
}
It seems you might be new to programming so here you go, your working program:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
void getLottoPicks(int userNums[], int size);
void genWinNums(int winNums[], int size);
int main()
{
const int size = 7;
int UserTicket[size];
int WinningNums[size];
char selection;
string name;
do
{
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "q) Quit Program" << endl;
cout << "Please make a selection : " << endl;
cin >> selection;
if (selection == '1')
{
cout << "Please enter your name: " << endl;
cin.ignore();
getline(cin, name);
getLottoPicks(UserTicket, size);
genWinNums(WinningNums, size);
cout << name << "'s LOTTO RESULTS" << endl;
cout << "----------------------" << endl;
cout << "WINNING TICKET NUMBERS : " << endl;
for(int i = 0; i < size; i++){
cout << WinningNums[i] << " ";
}
cout << endl;
cout << name << "'s TICKET : " << endl;
for(int i = 0; i < size; i++){
cout << UserTicket[i] << " ";
}
cout << endl;
}
else if (selection == 'q')
{
cout << "You have chosen to quit the program. Thank you for using!" << endl;
}
else
{
cout << "Invalid selection. Please try again." << endl;
}
} while (selection != 'q');
return 0;
}
void getLottoPicks(int userNums[], int size)
{
for (int times = 0; times < size; times++)
{
int input;
cout << "selection #" << times + 1 << ": " << endl;
cin >> input;
bool isNotDuplicate = true;
for (int i = 0; i < times; i++)
{
if (userNums[i] == input)
{
isNotDuplicate = false;
}
}
if (isNotDuplicate == true)
{
userNums[times] = input;
}
else
{
cout << "You already picked this number. Please enter a different number: " <<
endl;
times--;
}
}
}
void genWinNums(int winNums[], int size)
{
srand((unsigned int)time(NULL));
for (int times = 0; times < size; times++)
{
int i;
bool isNotDuplicate = true;
while (isNotDuplicate)
{
isNotDuplicate = false;
i = 1 + rand() % 40;
for (int j = 0; j < times; j++)
{
if (i == winNums[j])
{
isNotDuplicate = true;
}
}
}
winNums[times] = i;
}
}
As you can see, it is pretty easy to loop through an array. Maybe have a look at this for more info on arrays.
Most of the examples show "classic" C++, instead of the more modern variants.
So here's my take on your code :
#include <algorithm>
#include <array>
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
// compile time constant, in many C++ examples this is done with a #define/MACRO
constexpr int number_of_lotto_numbers = 7;
constexpr char play_lotto_char = '1';
constexpr char quit_lotto_char = 'q';
// use std::array instead of int values[]; since this has automatic bound checking!
// no reading/writing beyond array limits is allowed
// I use, using here to make code a bit more readable further down the line
// it lets code show intent instead of implementation
using lotto_numbers_t = std::array<int, number_of_lotto_numbers>;
// do not return arrays by passing arguments, just return an array
// don't worry about this making extra (class) copies c++ knows how to optimize this
lotto_numbers_t get_lotto_picks()
{
lotto_numbers_t lotto_numbers;
auto lotto_numbers_entered{ 0 };
while ( lotto_numbers_entered < number_of_lotto_numbers )
{
int input{ 0 };
std::cout << "selection #" << lotto_numbers_entered + 1 << ": " << std::endl;
std::cin >> input;
// use std::find for finding items in collections, if it finds the end of a collection then
// the value is not found.
if (std::find(lotto_numbers.begin(), lotto_numbers.end(), input) == lotto_numbers.end())
{
// lotto number not found so add it
lotto_numbers[lotto_numbers_entered] = input;
lotto_numbers_entered++;
}
else
{
// lotto number already in array so do not add it but give a message
std::cout << "You already entered this number, try another number" << std::endl;
}
}
return lotto_numbers;
}
lotto_numbers_t generate_winning_numbers()
{
lotto_numbers_t lotto_numbers;
auto lotto_numbers_generated{ 0 };
std::srand((unsigned int)time(NULL));
do
{
int new_number = (std::rand() % 40) + 1;
if (std::find(lotto_numbers.begin(), lotto_numbers.end(), new_number) == lotto_numbers.end())
{
// number not yet found
lotto_numbers[lotto_numbers_generated] = new_number;
lotto_numbers_generated++;
}
} while (lotto_numbers_generated < number_of_lotto_numbers);
return lotto_numbers;
}
void play_lotto()
{
char selection{ 0 }; // always initialize variables!
std::string name;
do
{
std::cout << "LITTLETON CITY LOTTO MODEL: " << std::endl;
std::cout << "---------------------------" << std::endl;
std::cout << "1) Play Lotto" << std::endl;
std::cout << "q) Quit Program" << std::endl;
std::cout << "Please make a selection : " << std::endl;
std::cin >> selection;
if (selection == play_lotto_char)
{
std::cout << "Please enter your name: " << std::endl;
std::cin.ignore();
std::getline(std::cin, name);
auto picked_numbers = get_lotto_picks();
auto winning_numbers = generate_winning_numbers();
std::cout << name << "'s LOTTO RESULTS" << std::endl;
std::cout << "----------------------" << std::endl;
std::cout << "WINNING TICKET NUMBERS : " << std::endl;
for (const auto number : winning_numbers)
{
std::cout << number << " ";
}
std::cout << std::endl;
std::cout << name << "'s TICKET : " << std::endl;
for (const auto number : picked_numbers)
{
std::cout << number << " ";
}
std::cout << std::endl;
if (picked_numbers == winning_numbers)
{
std::cout << "you have won!" << std::endl;
}
}
else if (selection == quit_lotto_char)
{
std::cout << "You have chosen to quit the program. Thank you for using!" << std::endl;
}
else
{
std::cout << "Invalid selection. Please try again." << std::endl;
}
} while (selection != quit_lotto_char);
}
Don't hesitate to ask questions on this code if you have any :)

guessing game while loop not looping

#include <iostream>
using namespace std;
bool play_game(int n) {
int guess;
bool noguesses = false;
int numofguesses = 0;
cout << "Welcome to my number guessing game\n";
while (n!=guess && !noguesses)
{
if (numofguesses < 6)
{
cout << "\n";
cout << "Enter your guess: ";
cin >> guess;
cout << "\n";
cout << "You entered: " << guess;
numofguesses++;
return false;
}
else
{
oog = true;
}
}
if (noguesses) {
cout << "I'm sorry. You didn't find my number.\n";
cout << "It was" << n << endl;
}
else
{
cout << "\n";
cout << "You found it in" << numofguesses << "guess(es)\n";
return true;
}
}
int main()
{
int secretnum = 5;
play_game(secretnum);
}
When I run this, the program stops after cout << "You entered: " << guess;. I want it to keep looping until the number of guesses reaches 6, or until the user inputs the correct answer.
Remove return false;
if (numofguesses < 6)
{
cout << "\n";
cout << "Enter your guess: ";
cin >> guess;
cout << "\n";
cout << "You entered: " << guess;
numofguesses++;
return false; //Remove this line
}

Hangman only gets first letter of secret word

I am trying to write a hangman program for an assignment. I've written code I thought would work, yet when testing it with the secret word, "IMPOSSIBLE", it only reads the "I" and nothing else. I tried changing all my strings to character lists but I don't think that was the issue. Does anyone have any advice on what I am doing incorrectly?
Thanks,
Keith.
Here is the code:
/* CSCI 261 Assignment 5: Hang Man Game
*
* Author: Keith Danielson
*
* A program that runs a simple hang man game
*/
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
//const string SECRET_WORD = "IMPOSSIBLE";
int main() {
const char SECRET_WORD[10] = {'I','M','P','O','S','S','I','B','L','E'};
const int SECRET_WORD_LENGTH = 10;
//Defining the number of wrong guesses available, found letters, wrong guesses, and user choice.
int guesses = 7;
char foundLetters[SECRET_WORD_LENGTH];
char wrongGuesses[guesses];
char userChoice;
//Filling foundLetters with underslashes based on the length of the secret word.
for (int i = 0; i <= SECRET_WORD_LENGTH; i++) {
foundLetters[i] = '_';
}
cout << "Welcome to hangman!" << endl;
for (int i = 0; i <= 7; i++) {
if (guesses == 0){
break;
}
cout << "Take a guess: ";
for (int j = 0; j <= SECRET_WORD_LENGTH; j++) {
cout << foundLetters[j] << " ";
}
cout << "\n" << "Your guess: ";
cin >> userChoice;
//if the user input is lowercase it'll be made upper case.
if (islower(userChoice)) {
userChoice = toupper(userChoice);
}
for (int j = 0; j <= SECRET_WORD_LENGTH; j++) {
//if (userChoice == foundLetters[j]) {
// cout << "You already guessed" << userChoice << "." << endl;
// break;
//}
if (userChoice == SECRET_WORD[j]) {
cout << "There's a " << userChoice << "!" << endl;
foundLetters[j] = userChoice;
break;
}
else if (userChoice != SECRET_WORD[j]) {
guesses = guesses - 1;
cout << "Sorry. No " << userChoice << "'s." << endl;
wrongGuesses[i] = userChoice;
if (guesses == 0) {
cout << "You lose! Try again.";
break;
}
else {
cout << "You have " << guesses << " remaining." << endl;
break;
}
}
}
}
return 0; // signals the operating system that our program ended OK.
}
Try something more like this instead:
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
#include <limits>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
const char SECRET_WORD[10] = {'I','M','P','O','S','S','I','B','L','E'};
const int SECRET_WORD_LENGTH = 10;
//Defining the number of wrong guesses available
const int WRONG_GUESSES = 7;
bool hasLetter(const char *letters, int numLetters, char ch) {
for (int i = 0; i < numLetters; ++i) {
if (letters[i] == ch) {
return true;
}
}
return false;
}
int main() {
char foundLetters[SECRET_WORD_LENGTH];
int foundLetters = 0;
char wrongLetters[WRONG_GUESSES];
int wrongLettersLength = 0;
int wrongGuessesLeft = WRONG_GUESSES;
char userChoice;
int found;
//Filling foundLetters with underslashes based on the length of the secret word.
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
foundLetters[j] = '_';
}
cout << "Welcome to hangman!" << endl;
while (true) {
cout << "Take a guess: ";
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
cout << foundLetters[j] << " ";
}
cout << "\n";
cout << "Your guess: ";
cin >> userChoice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//if the user input is lowercase it'll be made upper case.
userChoice = toupper(userChoice);
if (hasLetter(foundLetters, SECRET_WORD_LENGTH, userChoice) ||
hasLetter(wrongGuesses, wrongGuessesLength, userChoice))
{
cout << "You already guessed " << userChoice << "." << endl;
continue;
}
found = 0;
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
if (SECRET_WORD[j] == userChoice) {
foundLetters[j] = userChoice;
++found;
}
}
if (found > 0) {
cout << "There's " << found << " " << userChoice << (found > 1 ? "'s" : "") << "!" << endl;
foundLettersLength += found;
if (foundLettersLength == SECRET_WORD_LENGTH) {
cout << "You win!";
break;
}
}
else {
cout << "Sorry. No " << userChoice << "'s." << endl;
wrongLetters[wrongLettersLength++] = userChoice;
if (--wrongGuessesLeft == 0) {
cout << "You lose! Try again.";
break;
}
cout << "You have " << wrongGuessesLeft << " guess" << (wrongGuessesLeft > 1 ? "es" : "") << " remaining." << endl;
}
}
return 0; // signals the operating system that our program ended OK.
}
Alternatively:
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
#include <limits>
#include <set>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
const string SECRET_WORD = "IMPOSSIBLE";
//Defining the number of wrong guesses available
const int WRONG_GUESSES = 7;
int main() {
//Filling foundLetters with underslashes based on the length of the secret word.
string foundLetters(SECRET_WORD.size(), '_');
set<char> guessedLetters;
int wrongGuessesLeft = WRONG_GUESSES;
char userChoice;
int found;
cout << "Welcome to hangman!" << endl;
while (true) {
cout << "Take a guess: ";
for (int j = 0; j < foundLetters.size(); ++j) {
cout << foundLetters[j] << " ";
}
cout << "\n";
cout << "Your guess: ";
cin >> userChoice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//if the user input is lowercase it'll be made upper case.
userChoice = toupper(userChoice);
if (!guessedLetters.insert(userChoice).second)
{
cout << "You already guessed " << userChoice << "." << endl;
continue;
}
string::size_type pos = SECRET_WORD.find(userChoice);
if (pos != string::npos) {
found = 0;
do {
foundLetters[pos] = userChoice;
++found;
pos = SECRET_WORD.find(userChoice, pos+1);
}
while (pos != string::npos);
cout << "There's " << found << " " << userChoice << (found > 1 ? "'s" : "") << "!" << endl;
if (foundLetters == SECRET_WORD) {
cout << "You win!";
break;
}
}
else {
cout << "Sorry. No " << userChoice << "'s." << endl;
if (--wrongGuessesLeft == 0) {
cout << "You lose! Try again.";
break;
}
cout << "You have " << wrongGuessesLeft << " guess" << (wrongGuessesLeft > 1 ? "es" : "") << " remaining." << endl;
}
}
return 0; // signals the operating system that our program ended OK.
}

I am getting the linking errors in my C++ program, I could not compile my code

Error 1 error LNK2005: "class bus bs" (?bs##3Vbus##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\main.obj Project17
Error 2 error LNK2005: "class ticket tick" (?tick##3Vticket##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\main.obj Project17
Error 3 error LNK2005: "class ticket tick" (?tick##3Vticket##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\ticket.obj Project17
Error 4 error LNK2005: "class bus bs" (?bs##3Vbus##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\ticket.obj Project17
Error 5 error LNK1169: one or more multiply defined symbols found c:\users\tahir\documents\visual studio 2013\Projects\Project17\Debug\Project17.exe 1 1 Project17
bus.h
#pragma once
class bus
{
int busno;
int noofkidsseats;
int noofwomenseats;
int noofmenseats;
int noofspecialseats;
int noofvvip;
char *busname;
char *startpoint;
char *destination;
public:
bus();
void input();
int rbusno();
int rnoofkidsseats();
int rnoofwomenseats();
int rnoofmenseats();
int rnoofspecialseats();
int rnoofvvip();
void display();
}bs;
bus.cpp
#include <iostream>
#include <fstream>
#include "bus.h"
#include "ticket.h"
#include "windows.h"
using namespace std;
int length(char arr[])
{
int i = 0;
for (; arr[i] != '\0'; i++);
return i;
}
void gotoxy(int x, int y)
{
static HANDLE h = NULL;
if (!h)
h = GetStdHandle(STD_OUTPUT_HANDLE);
COORD c = { x, y };
SetConsoleCursorPosition(h, c);
}
bus::bus()
{
busno = 0;
noofkidsseats = 0;
noofwomenseats = 0;
noofmenseats = 0;
noofspecialseats = 0;
noofvvip = 0;
busname = '\0';
startpoint = '\0';
destination = '\0';
}
int bus::rbusno()
{
return busno;
}
int bus::rnoofkidsseats()
{
return noofkidsseats;
}
int bus::rnoofwomenseats()
{
return noofwomenseats;
}
int bus::rnoofmenseats()
{
return noofmenseats;
}
int bus::rnoofspecialseats()
{
return noofspecialseats;
}
int bus::rnoofvvip()
{
return noofvvip;
}
void bus::input()
{
cout << "ENTER THE BUS NUMBER: ";
cin >> busno;
cout << "ENTER THE NUMBER OF SEATS FOR KIDS: ";
cin >> noofkidsseats;
cout << "ENTER THE NUMBER OF SEATS FOR WOMEN: ";
cin >> noofwomenseats;
cout << "ENTER THE NUMBER OF SEATS FOR MEN: ";
cin >> noofmenseats;
cout << "ENTER THE NUMBER OF SEATS SPECIAL PERSONS: ";
cin >> noofspecialseats;
cout << "ENTER THE NUMBER OF SEATS FOR VVIP PASSENGERS: ";
cin >> noofvvip;
cout << "ENTER THE BUS NAME: ";
char name[20];
cin >> name;
int l = length(name);
busname = new char[l];
int i;
for (i = 0; i < l; i++)
busname[i] = name[i];
busname[i] = '\0';
cout << "ENTER THE STARTING POINT: ";
char start[20];
cin >> start;
int L = length(start);
startpoint = new char[L];
int j;
for (j = 0; j < L; j++)
startpoint[j] = start[j];
startpoint[j] = '\0';
cout << "ENTER THE DESTINATION: ";
char end[20];
cin >> end;
int s = length(end);
destination = new char[s];
int k;
for (k = 0; k < s; k++)
destination[k] = end[k];
destination[k] = '\0';
}
void bus::display()
{
cout << " ***************************************" << endl;
cout << " * *" << endl;
cout << " * BUS DEATAILS *" << endl;
cout << " * *" << endl;
cout << " ***************************************" << endl;
cout << " THE BUS NUMBER: ";
cout << busno << endl;
cout << " THE BUS NAME: ";
cout << busname << endl;
cout << " STARTING POINT: ";
cout << startpoint << endl;
cout << " DESTINATION: ";
cout << destination << endl;
cout << " THE NUMBER OF SEATS FOR KIDS: ";
cout << noofkidsseats << endl;
cout << " THE NUMBER OF SEATS FOR WOMEN: ";
cout << noofwomenseats << endl;
cout << " THE NUMBER OF SEATS FOR MEN: ";
cout << noofmenseats << endl;
cout << " THE NUMBER OF SEATS SPECIAL PERSONS: ";
cout << noofspecialseats << endl;
cout << " THE NUMBER OF SEATS FOR VVIP PASSENGERS: ";
cout << noofvvip << endl;
}
ticket.h
#pragma once
class ticket
{
int resno;
int age;
int tokids;
int towomen;
int tomen;
int tospecial;
int tovvip;
int noofkidsseats;
int noofwomenseats;
int noofmenseats;
int noofspecialseats;
int noofvvip;
char *pname;
char *status;
public:
ticket();
void reservation();
int returnresno();
void cancellation();
void print();
}tick;
ticket.cpp
#include <iostream>
#include <fstream>
#include <string>
#include "ticket.h"
#include "bus.h"
using namespace std;
ticket::ticket()
{
resno = 0;
age = 0;
tokids = 0;
towomen = 0;
tomen = 0;
tospecial = 0;
tovvip = 0;
pname = '\0';
status = '\0';
}
int ticket::returnresno()
{
return resno;
}
void ticket::print()
{
int f = 0;
system("cls");
ifstream fn("Ticket1.dat", ios::out); fn.seekg(0);
if (!fn)
{
cout << "ERROR IN THE FILE ";
}
X:
cout << "ENTER THE RESERVATION NO ";
int n;
cin >> n;
while (!fn.eof())
{
fn.read((char*)&tick, sizeof(tick));
if (n == resno)
{
f = 1;
system("cls");
cout << "NAME: ";
cout << pname;
cout << "AGE: ";
cout << age;
cout << "PRESENT STATUS: ";
cout << status;
cout << "RESERVATION NUMBER: ";
cout << resno;
cout << "PRESS ANY KEY TO CONTINUE ";
system("pause");
}
}
if (f == 0)
{
system("cls");
cout << "UNRECOGINIZED RESERVATION NO !!! WANNA RETRY ? (Y / N) ";
char a;
cin >> a;
if (a == 'y' || a == 'Y')
{
system("cls");
goto X;
}
else
{
cout << "PRESS ANY KEY TO CONTINUE";
system("pause");
}
}
fn.close();
}
void ticket::reservation()
{
system("cls");
cout << "RESERVATION ";
cout << "ENTER THE BUS NO: ";
int bno, f = 0; cin >> bno; ofstream file;
ifstream fin("bus1.dat", ios::out); fin.seekg(0);
if (!fin)
{
system("cls");
cout << "ERROR IN THE FILE ";
system("cls");
while (!fin.eof())
{
fin.read((char*)&bs, sizeof(bs)); int z;
z = bs.rbusno();
if (bno == z)
{
f = 1;
noofkidsseats = bs.rnoofkidsseats();
noofwomenseats = bs.rnoofwomenseats();
noofmenseats = bs.rnoofmenseats();
noofspecialseats = bs.rnoofspecialseats();
noofvvip = bs.rnoofvvip();
}
}
if (f == 1)
{
file.open("Ticket1.dat", ios::app);
S:
system("cls");
cout << "NAME:";
cin >> pname;
cout << "AGE:";
cin >> age;
system("cls");
cout << "SELECT THE CATEGORY WHICH YOU WISH TO TRAVEL";
cout << "1.KIDS CATEGORY: ";
cout << "2.WOMEN CATEGORY: ";
cout << "3.MEN CATEGORY: ";
cout << "4.SPECIAL CATEGORY: ";
cout << "5.SECOND CLASS SLEEPER: ";
cout << "ENTER YOUR CHOICE ";
int c;
cin >> c;
switch (c)
{
case 1:
tokids++;
resno = rand();
if ((noofkidsseats - tokids)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 2:
towomen++;
resno = rand();
if ((noofwomenseats - towomen)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO:";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 3:
tomen++;
resno = rand();
if ((noofmenseats - tomen)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
else
{
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 4:
tospecial++;
resno = rand();
if ((noofspecialseats - tospecial)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
else
{
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 5:
tovvip++;
resno = rand();
if ((noofvvip - tovvip)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
else
{
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
}
cout << "DO YOU WISH TO CONTINUE BOOKING TICKETS (Y/N) ? ";
char n;
cin >> n;
if (n == 'y' || n == 'Y')
{
goto S;
}
}
}
if (f == 0)
{
system("cls");
cout << "ERROR IN THE BUS NUMBER ENTERED !!!";
system("pause");
}
file.close();
}
void ticket::cancellation()
{
system("cls");
ifstream fin;
fin.open("Ticket1.dat", ios::out);
ofstream file;
file.open("Temp1.dat", ios::app);
fin.seekg(0);
cout << "ENTER THE RESERVATION NO: ";
int r, f = 0;
cin >> r;
if (!fin)
{
cout << "ERROR IN THE FILE !!!";
}
while (!fin.eof())
{
fin.read((char*)&tick, sizeof(tick)); int z;
z = returnresno();
if (z != r)
{
file.write((char*)&tick, sizeof(tick));
}
if (z == r)
{
f = 1;
}
}
file.close(); fin.close();
remove("Ticket1.dat");
rename("Temp1.dat", "Ticket1.dat");
if (f == 0)
{
cout << "NO SUCH RESERVATION IS MADE !!! PLEASE RETRY ";
system("pause");
}
else
{
cout << "RESERVATION CANCELLED";
system("pause");
}
}
main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include "bus.h"
#include "ticket.h"
using namespace std;
int main()
{
ticket obj;
bus obj1;
int ch, r = 1000, j;
cout << "WELCOME";
Z:
cout << "BUS TICKET RESERVATION";
cout << "==========================";
cout << "1.BUS DETAILS";
cout << "2.UPDATE BUS DETAILS ";
cout << "3.RESERVING A TICKET ";
cout << "4.CANCELLING A TICKET";
cout << "5.DISPLAY THE PRESENT TICKET STATUS ";
cout << "6.EXIT";
cout << "ENTER YOUR CHOICE: ";
cin >> ch;
char n;
switch (ch)
{
case 1:
{
ifstream fin("bus1.dat", ios::out);
fin.seekg(0);
if (!fin)
{
cout << "ERROR IN THE FILE !!!";
}
else
{
while (!fin.eof())
{
fin.read((char*)&obj1, sizeof(obj1));
bs.display();
}
}
fin.close();
goto Z;
}
case 2:
{
cout << "ENTER THE PASSWORD ";
cin >> j;
cout << "CHECKING PLEASE WAIT ";
system("pause");
Y:
ofstream fout("bus1.dat", ios::app);
bs.input();
fout.write((char*)&obj1, sizeof(obj1));
fout.close();
cout << "DO YOU WISH TO CONTINUE UPDATING ?(Y/N)";
cin >> n;
if (n == 'y' || n == 'Y')
{
goto Y;
goto Z;
}
else
{
goto Z;
}
}
case 3:
{
obj.reservation();
goto Z;
}
case 4:
{
obj.cancellation();
goto Z;
}
case 5:
{
obj.print();
goto Z;
}
case 6:
{
exit(0);
}
}
system("pause");
return 0;
}
class bus
{
// members
}bs;
Not only declares a type bus but also a defines a variable bs. The same for tick.
When you include these headers in several cpp files, you get several definitions of these variables.
I'm sure none of the C++ books you have read told you to define variables like this in header files, so just don't. Declare the types in the headers and the variables where you need them, likely in the cpp files.