When I debug my program, it outputs a random stream of characters when outputting the asterisked line.
int main ()
{
string inputPuzzle;
cout << "Enter a word or set of words: ";
getline(cin, inputPuzzle);
char* puzzle = new char[inputPuzzle.size()+1];
memcpy(puzzle, inputPuzzle.c_str(), inputPuzzle.size()+1);
puzzle[inputPuzzle.size()+1] = '';
int strikes = 0;
char userInput;
char* userSoln = new char[inputPuzzle.size()];
for (int i = 0; i < inputPuzzle.size(); i++)
{
userSoln[i] = '-';
if (puzzle[i] == ' ')
{
userSoln[i] = ' ';
}
}
bool solved = false;
int numberOfLetters;
for (;;)
{
numberOfLetters = 0;
cin >> userInput;
for (int i = 0; i < inputPuzzle.size(); i++)
{
if (userInput == puzzle[i])
{
numberOfLetters++;
userSoln[i] = puzzle[i];
}
}
if (numberOfLetters == 0)
{
cout << "There are no " << userInput << "'s\n" ;
strikes++;
}
else
{
cout << "There are " << numberOfLetters << " " << userInput << "'s\n";
}
if (userSoln == puzzle)
{
break;
}
if (strikes == 10)
{
break;
}
**cout << "PUZZLE: " << userSoln << "\n";**
cout << "NUMBER OF STRIKES: " << strikes << "\n";
}
if (strikes == 10)
{
cout << "Sorry, but you lost. The puzzle was: " << puzzle;
}
else
{
cout << "Congratulations, you've solved the puzzle!!! YOU WIN!!!!!";
}
}
I've tried clearing cin buffers, but nothing doing. I have all the necessary include files (string and iostream) too, so that isn't the issue, and i have the namespace std above the main method.
This isn't a valid character constant.
puzzle[inputPuzzle.size()+1] = '';
If you intended a terminating character, it should be
puzzle[inputPuzzle.size()+1] = '\0';
or just
puzzle[inputPuzzle.size()+1] = 0;
or you could replace both these lines
memcpy(puzzle, inputPuzzle.c_str(), inputPuzzle.size()+1);
puzzle[inputPuzzle.size()+1] = '';
with strcpy
strcpy(puzzle, inputPuzzle.c_str());
Edit:
You also need to put a terminating character at the end of userSoln before printing it.
userSoln[ inputPuzzle.size() ] = '\0';
puzzle[inputPuzzle.size()+1] = '';
should be
puzzle[inputPuzzle.size()+1] = '\0';
you were trying to add the null terminator to the end of the string to signify the end, but '' is not quite it.
Related
This is a hangman game program. I am declaring a char*p in the main which I can't understand why I am unable to delete later in the program when I don't need it. I tried it deleting later but it gives a heap memory error.
Also, I am a newbie in c++ - actually in programming - I will also appreciate if you can help me on how can I make the output of this program(on console) look more attractive and interactive. Like where should I use system("cls") commands more that can make it look more readable and remove non-essential information. Make a file in the same directory of the program with name either easy,medium or hard. so that it can have input from it when u run the program..
#pragma once
#include<iostream>
#include<string>
#include<ctime>
#include <cstdlib>
#include <stdlib.h>
#include <Windows.h>
#include<fstream>
#include<ctime>
#include <chrono> // for measuring time
using namespace std;
using namespace chrono;
//scoring the game with recard to time....
// filing : user name unique id and all that
//storing the name of user , his score, long story short, make a record of every user who passes by
int len = 0, letterCount = 0, size = 0, guesses = 6;
class tstamp
{
time_point<system_clock>tstart;
time_point<system_clock>tstop;
public:
void start()
{
tstart = system_clock::now();
}
void stop()
{
tstop = system_clock::now();
}
long long elasped()
{
return duration_cast<chrono::seconds>(tstop - tstart).count();
}
};
int checkWin(string a, char *p)
{
int count = 0;
int i = 0;
char *an = new char[a.length()];
string word = p;
for (i = 0; i < a.length(); i++)
{
if (a[i] == word[i])
count++;
}
if (count == i)
return 1; // 1 means the array is equal to the string == win
else
return 0; // not win
delete[]an; // using delete here for 1st
}
void resetData(string nameOfPlayer)
{
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::trunc);
//fout << "No Record";
fout.close();
}
void playerDetails(string nameOfPlayer, string a, bool status, float timeTaken)
{
char check = '\0';
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::app);
if (status == true)
fout << "Status : WON" << endl;
else
fout << "Status : LOST" << endl;
fout << "Word : " << a << endl;
fout << "Time taken to guess : " << timeTaken << " seconds" << endl;
fout << "********************************************";
fout << endl << endl;
fout.close();
}
string * grow(string *p, string temp) // to regrow the string array!!!!!
{
string* newArray = new string[size + 1];
for (int i = 0; i<size - 1; i++)
{
*(newArray + i) = *(p + i);
}
newArray[size - 1] = temp;
delete[] p;
return newArray;
}
char inGameMenu(char reset)
{
reset = '\0';
cout << "\n\t--->To reset your record press 'r' : ";
cout << "\n\n\t--->To display your previous record press 'd' : ";
cout << "\n\n\t--->To continue press 'x' : ";
cout << "\n\n\t--->To Exit the game press 'q' : ";
cout << endl << "\n\n\t--->Your Choice : ";
cin >> reset;
return reset;
}
string provideWord(string *contents, string a)
{
srand(time(NULL));
int i = rand() % size;
a = contents[i];
return a;
}
string* read(string fileName, string contents[])
{
string ext = ".txt";
fileName = fileName + ext;
fstream fin;
fin.open(fileName);
if (fin.is_open())
{
fin >> contents[0];
size++;
string temp;
while (fin >> temp)
{
size++;
contents = grow(contents, temp);
}
}
else
cout << "\n\tFile Not Found\n\n\n";
return contents;
}
char * makeAsterisks(string temp) // this will make astericks of the word player have to guess.
{
int len = temp.length();
char*p = new char[len];
for (int i = 0; i < len; i++)
{
p[i] = '-';
}
p[len] = '\0';
return p;
}
void displayRecord(string fileName, string display)
{
fstream fout;
fout.open(fileName + ".txt");
cout << "\n----------------------------------------------------------------------------------------------------------------";
if (fout.is_open())
{
cout << endl << endl;
while (getline(fout, display))
cout << display << endl;
}
else
cout << "\n!!No Record Found!!\nYou might be a new user\n";
cout << "\n----------------------------------------------------------------------------------------------------------------\n";
fout.close();
}
char * checkMyGuess(string word, char userGuess, char ar[])
{
bool flag = true;
for (int i = 0; i < word.length(); i++)
{
if (userGuess == word[i])
{
flag = false;
ar[i] = userGuess;
letterCount++;
}
}
if (flag == true)
{
_beep(450, 100);
cout << "\n\t!!!Wrong!!!\n";
len--;
guesses--;
}
return ar;
}
void rules()
{
system("Color 09 "); // for color effects
cout << "\n\n\t\t\t=====================\n";
cout << "\t\t\t||\tHANGMAN\t ||\n\t\t\t||\tRules\t ||"
<< "\n " << "\t\t\t=====================\n\n\n";
_beep(4000, 500);
system("Color 08 "); // for color effects
system("Color 07 "); // for color effects
cout << "\t--> Computer will think of a word and you have try\n" // rules
<< "\t to guess what it is one letter at a\n"
<< "\t time. Computer will draw a number of dashes \n "
<< "\tequivalent to the number of letters in the word.\n "
<< "\t If you suggest a letter that occurs\n "
<< "\t in the word, the computer will fill in the blank(s)\n"
<< "\t with that letter in the right place(s).\n"
<< "\t The session will be timed. \n\n";
cout << endl;
cout << "\t--> Total number of wrong choices : 6\n\n"; //wrong turns
cout << "\t--> Objective : Guess the word / phrase before you run out of choices!\n\n"; // obj
}
int checkForName(string fileName)
{
fileName = fileName + ".txt";
char line = '\0';
fstream fin;
char fromFile[7] = "\t\tName";
fin.open(fileName);
int i = 0,
check = 0;
while (fin.get(line) && i < 7)
{
if (line == fromFile[i++])
check++;
}
if (check == i - 1)
return 1;
else
return 0;
fin.close();
}
void checkForRecord(string fileName)
{
fileName = fileName + ".txt";
char line = '\0';
fstream fin;
char fromFile[7] = "No";
fin.open(fileName);
int i = 0,
check = 0;
while (fin.get(line) && i < 3)
{
if (line == fromFile[i++])
check++;
}
if (check == i - 1)
{
fin.open(fileName, ios::trunc);
fin.close();
}
fin.close();
}
int menu(int mode) // this function asks the user to enter the difficulty level of the game!!! You can't even beat medium!
{
system("cls");
cout << "Please select the Level of Game :\n";
cout << "1. Easy" << endl;
cout << "2. Medium" << endl;
cout << "3. Hard" << endl << endl;
cout << "Your Choice : ";
cin >> mode;
while (!(mode <= 3 && mode >= 1))
{
cout << endl << endl;
cout << "Please Enter the number of given choices: ";
cin >> mode;
}
return mode;
}
int comMenu(string nameOfPlayer, char reset)
{
string readData;
reset = '\0';
while (1)
{
reset = inGameMenu(reset);
if (reset == 'r')
{
resetData(nameOfPlayer);
system("cls");
Sleep(1);
}
else if (reset == 'd')
{
system("cls");
Sleep(1); // just to add a little delay!
cout << "Your Record Shows :--->\n";
displayRecord(nameOfPlayer, readData);
}
else if (reset == 'x')
break;
else if (reset == 'q')
break;
else
{
cout << "\n\n!!!Invalid Choice!!!\n\n";
}
}
return reset;
}
int main()
{
string nameOfPlayer;
char anyKey = '\0';
string name;
cout << endl;
rules();
cout << "Enter the name of player: ";
cin >> nameOfPlayer;
while (1)
{
char reset = '\0';
reset = comMenu(nameOfPlayer, reset);
if (reset != 'q') // check to exit the game
{
int uniquevar = checkForName(nameOfPlayer);
if (uniquevar != 1)
{
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::app);
fout << "\t\tName of Player : " << nameOfPlayer << endl << endl << endl;
fout.close();
}
while (1)
{
system("Color E0");
bool status = true; //initially win
size = 0,
len = 0,
letterCount = 0,
guesses = 6;
string a = ""; // it holds the word
string *contents = new string[1];
string name = "";
char b;
int mode = 0;
tstamp ts;
bool notRepeat[26] = { 0 };
if (anyKey == 'X' || anyKey == 'x')
break;
else
{
mode = menu(mode);
if (mode == 1)
name = "easy";
else if (mode == 2)
name = "medium";
else if (mode == 3)
name = "hard";
contents = read(name, contents);
cout << endl;
}
a = provideWord(contents, a);
delete[]contents;
len = a.length();
char *p = makeAsterisks(a); // detele it later
cout << "Total number of words to guesses: " << len << endl << endl;
cout << "Total guesses you have: 6\n";
cout << "Word :\n\n\t" << p << endl << endl;
ts.start(); // it starts counting the time...
while (guesses != 0)
{
cout << "Enter char: ";
cin >> b;
if (b >= '1' && b <= '9')
{
cout << "\n\nThere is not number in the given word\n\n";
continue;
}
int temp = b - 97; // it assigns the value of alphabet to temp i.e a=0,b=0 so on...
if (notRepeat[temp] != false)
{
cout << "\n\nYou've already used this word\n\n";
cout << "Remaining Choices: " << guesses << endl << endl;
continue;
}
else
{
p = checkMyGuess(a, b, p);
int checkingTheWin = checkWin(a, p);
if (checkingTheWin == 0)
{
}
else
{
cout << "\n\n\t*************You Won****************\n\n";
status = true; //true = win
break;
}
notRepeat[temp] = true;
cout << endl << endl;
cout << "Remaining Choices: " << guesses << endl;
cout << endl << '\t' << p << endl;
}
}
ts.stop();
cout << "Time Taken: " << ts.elasped() << " seconds\n\n";
p = NULL;
if (guesses == 0)
{
status = false; //false = lose
checkForRecord(nameOfPlayer);
playerDetails(nameOfPlayer, a, status, time); // right here it will create a file with the name of user
cout << "\n\nGame Over!!!\n\n";
cout << "\t\tThe word was \n\t\t\" " << a << "\"\n\n";
}
else
{
checkForRecord(nameOfPlayer);
playerDetails(nameOfPlayer, a, status, time); // right here it will create a file with the name of user
}
break;
} //ending block of while(1) first
system("color 07"); // shashka!!
}
if (reset == 'q') // to exit the game if the user decides so right away!!
break;
}
cout << "Exiting the Game\n\n";
_beep(3000, 500); // ending sound!
return 0;
}
In makeAsterisks you don't allow for the null terminator. You need to allocate one more character
char * makeAsterisks(string temp)
{
int len = temp.length();
char*p = new char[len + 1]; // <-- change here
for (int i = 0; i < len; i++)
{
p[i] = '-';
}
p[len] = '\0';
return p;
}
Now having said that, you are already using string, why not make life easier for yourself and use it everywhere? Here's makeAsterisks rewritten to use string.
string makeAsterisks(string temp)
{
return string(temp.length(), '-');
}
I'm writing a program where the user inputs a string and the user can then select from a menu to do things such as display the number of words in the string or number of spaces in the string. I have all functions working except for the one where I need to be able to find the number of instances of a specific word or phrase. Whenever I enter a word or phrase it says there are 0 occurrences. This is my entire code but again I just need help with my FindText function. Bare in mind I'm a beginner programmer.
#include <iostream>
#include <string>
using namespace std;
string user_text = " ";
string find_text = " ";
string replaced = " ";
char print_menu(char);
int GetNumOfNonWSCharacters(string);
int GetNumOfWords(string);
int FindText(string, string);
string ReplaceExclamation(string);
string ShortenSpace(string);
int main()
{
char choice = ' ';
cout << "Enter a sample text: ";
getline(cin, user_text);
choice = print_menu(choice);
while (!(choice == 'q'))
{
switch (choice)
{
case 'c': //number of non-whitespace characters
int not_space;
not_space = GetNumOfNonWSCharacters(user_text);
cout << "Number of non white space charactesr: " << not_space << endl;
choice = print_menu(choice);
break;
case 'w': //number of words
int words;
words = GetNumOfWords(user_text);
cout << "Number of words: " << words << endl;
choice = print_menu(choice);
break;
case 'f': //find text
int occurences;
cout << "Enter a word or phrase to be found: ";
cin.ignore();
getline(cin, find_text);
occurences = FindText(find_text, user_text);
cout << find_text << " instances: " << occurences << endl;
choice = print_menu(choice);
break;
case 'r': //replace all !'s
replaced = ReplaceExclamation(user_text);
cout << replaced << endl;
choice = print_menu(choice);
break;
case 's': //shorten spaces
replaced = ShortenSpace(user_text);
cout << replaced << endl;
choice == print_menu(choice);
break;
case 'q': //quit
exit(0);
break;
default:
cout << "Invalid choice please try again";
choice = print_menu(choice);
}
}
system("pause");
return 0;
}
char print_menu(char choice)
{
cout << "MENU" << endl;
cout << " c - Number of non - whitespace characters" << endl;
cout << " w - Number of words" << endl;
cout << " f - Find text" << endl;
cout << " r - Replace all !'s" << endl;
cout << " s - Shorten spaces" << endl;
cout << " q - Quit" << endl;
cout << " Choose an option ";
cin >> choice;
return choice;
}
int GetNumOfNonWSCharacters(string text)
{
int spaces = 0;
int not_spaces = text.length();
for (int i = 0; i < text.length(); i++)
{
if (isspace(text.at(i)) != false)
{
spaces += 1;
}
}
not_spaces = not_spaces - spaces;
return not_spaces;
}
int GetNumOfWords(string text)
{
int words = 0;
for (int i = 0; i < text.length(); i++)
{
if (text.at(i) == ' ')
{
words++;
}
}
return words + 1;
}
int FindText(string find, string text)
{
int count = 0;
for (int i = 0; i < text.length(); i++)
{
if (text.find(find) == true)
{
count++;
}
}
return count;
}
string ReplaceExclamation(string text)
{
for (int i = 0; i < text.length(); i++)
{
if (text.at(i) == '!')
{
text.at(i) = '.';
}
}
return text;
}
string ShortenSpace(string text)
{
for (int i = 0; i < text.length(); i++)
{
if (text.at(i) == ' ' && text.at(i + 1) == ' ')
{
text.erase(text.begin() + i);
}
}
return text;
}
string::find() returns size_type and not bool
Use an overload of find() that allows you to specify the starting position.
size_type find( const basic_string& str, size_type pos = 0 )
Once the string is found, add its length to the starting position and use find again to find the next occurrence.
You can modify your function thus:
int FindText(string find, string text)
{
int count = 0;
string::size_type start = 0;
while ((start = text.find(find, start)) != string::npos) {
++count;
start += find.length();
}
return count;
}
We are taking user input and reversing it in the background and asking the user what is the reverse. Then we compare realreverse and userreverse and say that it's correct or how many mistakes were made. Also we are counting sentences with using dots, and the user should end his input with #.
For example:
hi. how are you doing. #
or
hi bro how are u.
im good. #
The problem is my program is only working if the input doesn't contain any spaces.
hihowareyoudoing. thanksimfinebro #
If the input is like that, it's working.
it works
hihowareyoudoing.
thanksimfinebro. #
This 2 column also working
code:
(program shows correct inverse for testing)
#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
int wrongCount = 0;
if (reverseReal.length() != reverseUser.length()) {
cout << "These strings are not comparable." << endl;
}
else {
for (int i = 0; i < reverseReal.length(); i++) {
if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
wrongCount++;
}
}
cout << "Number of mistakes: " << wrongCount << endl;
if (wrongCount == 0){
cout << "gj correct reverse" << endl;
}
}
}
string getReverse(string sentence) {
string reverseResult = "";
for (int i = sentence.length() - 1; i >= 0; i--) {
reverseResult += sentence.substr(i, 1);
}
return reverseResult;
}
int findsnumber(string snumber)
{
unsigned int sentences = 0, index = 0, length;
string searchPattern = ".";
length = snumber.length();
while (index < length)
{
index = snumber.find(searchPattern, index);
if (index != string::npos)
{
index += searchPattern.length();
sentences++;
}
}
return sentences;
}
// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
while (sentence.find(".") != string::npos) {
int dotFinder = 0;
string sub = "";
dotFinder = sentence.find(".");
sub = sentence.substr(0, dotFinder);
return sub;
}
return "";
}
int main() {
string input = "";
string result = "";
string reverseReal = "";
int i = 1;
cout << "Welcome to my cancer c++ programme." << endl;
cout << "Enter the paragraph with # at the end to end it:" << endl;
while (cin >> input && input != "#") {
result += input + " ";
}
int sentnumber = findsnumber(result);
cout << "Number of sentences in the given string " << sentnumber << endl;
while (result.find(".") != string::npos) {
string sub = "";
string subReverse = "";
string reverse = "";
string reverseson = "";
cout << i << "/" << sentnumber << endl;
sub = getOneSentence(result);
subReverse = getReverse(sub);
cout << "reverse of the sub " << subReverse << endl;
cout << "Sentence " << i << " : " << sub << endl;
cout << "Enter the reverse of your sentence" << endl;
while (cin >> reverse && reverse != "#"){
reverseson += reverse + "";
}
Comparison(subReverse, reverseson);
result = result.substr(result.find(".") + 2, result.length());
i++;
}
cin.ignore();
cin.get();
}
cin does not support input string with spaces. So, to input a string containing spaces you need to use getline()The correct syntax is std::getline(std::cin, input);
Edited Your Code!
#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
int wrongCount = 0;
if (reverseReal.length() != reverseUser.length()) {
cout << "These strings are not comparable." << endl;
}
else {
for (int i = 0; i < reverseReal.length(); i++) {
if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
wrongCount++;
}
}
cout << "Number of mistakes: " << wrongCount << endl;
if (wrongCount == 0){
cout << "gj correct reverse" << endl;
}
}
}
string getReverse(string sentence) {
string reverseResult = "";
for (int i = sentence.length() - 1; i >= 0; i--) {
reverseResult += sentence.substr(i, 1);
}
return reverseResult;
}
int findsnumber(string snumber)
{
unsigned int sentences = 0, index = 0, length;
string searchPattern = ".";
length = snumber.length();
while (index < length)
{
index = snumber.find(searchPattern, index);
if (index != string::npos)
{
index += searchPattern.length();
sentences++;
}
}
return sentences;
}
// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
while (sentence.find(".") != string::npos) {
int dotFinder = 0;
string sub = "";
dotFinder = sentence.find(".");
sub = sentence.substr(0, dotFinder);
return sub;
}
return "";
}
int main() {
//char input = '\0';
string input = "";
string result = "";
string reverseReal = "";
int i = 1;
cout << "Welcome to my cancer c++ programme." << endl;
cout << "Enter the paragraph with # at the end to end it:" << endl;
getline(cin, input,'#');
result = input;
int sentnumber = findsnumber(result);
cin.clear();
cout << "Number of sentences in the given string " << sentnumber << endl;
while (result.find(".") != string::npos) {
string sub = "";
string subReverse = "";
string reverse = "";
string reverseson = "";
cout << i << "/" << sentnumber << endl;
sub = getOneSentence(result);
subReverse = getReverse(sub);
cout << "reverse of the sub " << subReverse << endl;
cout << "Sentence " << i << " : " << sub << endl;
cout << "Enter the reverse of your sentence" << endl;
cin.clear();
cin.ignore();
getline(cin,reverse,'#');
reverse.erase(reverse.end() - 1, reverse.end());
reverseson = reverse;
Comparison(subReverse, reverseson);
result = result.substr(result.find(".") + 2, result.length());
i++;
}
system("pause");
}
I am having a bug that I cannot find a fix for through google searching. I am attempting to make a text based version of the game Mastermind. I am using a string the is set from an array of chars as the criteria for a while loop. When the string is equal to "****" the game is supposed to tell the player that they won and exit, but for some reason a ^A is being added on to the end of the string that is being checked, even though it is not in the char array.
Here is the function that sets the char array and returns a string from that array:
string check(int guess[4], int num[4]) {
char hints[4];
cout << " ";
for (int i = 0; i < 4; i++) {
if (guess[i] == num[i]) {
hints[i] = '*';
cout << "*";
}
else {
for (int x = 0; x < 4; x++) {
if (guess[i] == num[x]) {
cout << "+";
}
}
}
if (guess[i] != num[i]) {
hints[i] = ' ';
}
}
string hint(hints);
cout << endl;
cout << hint << endl;
return hint;
}
And here is the function checking the value of the string:
while (hints.compare("****") != 0) {
if (guessCount == 5) {
break;
}
cout << "Guess?: ";
cin >> guess;
intToArray(guess, guessArr);
hints = check(guessArr, nums);
cout << hints << endl;
guessCount++;
}
if (hints.compare("****") == 0) {
cout << "You win! The number was: ";
for (int i = 0; i < 4; i++) {
cout << nums[i];
}
}
You haven't null-terminated the hints array, so you are getting extra garbage that is lying around on the stack in your string.
You could let the hint string know how long it is when you are constructing it.
string hint(hints, 4);
cout << endl;
cout << hint << endl;
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 8 years ago.
Improve this question
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
const int MAX_NUMS = 200; // Constant for the maximum number of words.
const int MAX_GUESSES = 8;
const string LETTERS = "abcdefghijklmnopqrstuvwxyz";
char inputLetter();
int findChar(char letter, string&word);
string getGuessedWord(string&secretWord, string&lettersGuessed);
string getLettersGuessed(char letter, string&lettersGuessed, int n);
void display(string&lettersGuessed, string&wordGuessed, int num, int pos);
bool isDone(string wordGuessed);
int main()
{
string oneWord; // holds one word from input file
string secretWord; // holds secret word to be guessed
string words[MAX_NUMS]; // holds list of words from input file
int randomValue; // holds index of secret word
int count = 0; // holds number of words in the file
// Declare an ifstream object named myFile and open an input file
ifstream myFile;
myFile.open("P4Words.txt");
// Exit program if cannot open file for input
if (!myFile)
{
cout << "Error: Unable to open file for input" << endl;
return 0;
}
// Input words from a file into words array
// Add your code here ...
myFile >> oneWord;
while (!myFile.eof())
{
words[count] = oneWord;
count++;
myFile >> oneWord;
}
myFile.close();
cout << count << " words loaded." << endl;
srand(static_cast<unsigned int>(time(0)));
// Select a secret word
// Add your code here ...
secretWord = words[rand() % (count + 1) ];
// Possible useful variables the loop
string lettersGuessed = ""; // holds letters guessed so far
string wordGuessed; // holds current word guessed like �_ pp_ e�
int incorrectGuesses = 0; // holds number of incorrect guesses so far
char letter; // holds a guessed letter
bool done = false; // have not guessed the word yet
int num = 8; int pos;
cout << "Welcome to the game, Hangman V1 by Your Name!" << endl;
cout << "I am thinking of a word that is " << secretWord.length()
<< " letters long." << endl;
// Set up a loop to input guesses and process
// Add your code here ...
do
{
letter = inputLetter();
pos = findChar(letter, secretWord);
wordGuessed = letter;
lettersGuessed = getLettersGuessed(letter, lettersGuessed, 8 - num);
wordGuessed = getGuessedWord(secretWord, lettersGuessed);
display(lettersGuessed, wordGuessed, num, pos);
done = isDone(wordGuessed);
num--;
} while ((num > 1) && (done == false));
// Check for won or lost
// Add your code here ...
if (done == false)
{
cout << "sorry you lose..." << endl;
}
if (done == true)
{
cout << "congratulations! " << endl;
}
system("pause"); // stop program from closing, Windows OS only
return 0;
}
// Add function definitions here ...
char inputLetter()
{
int i;
char letter;
do
{
cout << "please guess a letter: " << endl;
cin >> letter;
for (i = 0; i < 25; i++)
{
if (letter == LETTERS[i])
{
return letter;
}
}
if (letter != LETTERS[i])
{
cout << "Oops! That is an invalid character." << endl;
}
} while (letter != LETTERS[i]);
}
int findChar(char letter, string &word)
{
int i = 0; int pos = 0; bool found = false;
do
{
if (word[pos] == letter)
{
return pos;
found = true;
}
pos++;
} while (pos<word.length() - 1);
if (found == false)
{
return -1;
}
}
string getGuessedWord(string&secretWord, string&letterGuessed)
{
string temp;
temp = secretWord;
for (size_t k = 0; k <= temp.length() - 1; k++)
{
temp[k] = '_';
}
for (size_t i = 0; i <= temp.length() - 1; i++)
{
for (size_t j = 0; j <= temp.length() - 1; j++)
{
if (letterGuessed[i] == secretWord[j])
{
temp[j] = letterGuessed[i];
}
}
}
return temp;
}
string getLettersGuessed(char letter, string&lettersGuessed, int n)
{
string temp;
temp = letter;
lettersGuessed.insert(n, temp);
return lettersGuessed;
}
void display(string&lettersGuessed, string&wordGuessed, int num, int pos)
{
if (pos != -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Good guess!: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
if (pos == -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Oops! that letter is not my word: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
}
bool isDone(string wordGuessed)
{
bool done = false; int k = 0;
for (size_t i = 0; i <= wordGuessed.length() - 1; i++)
{
if (wordGuessed[i] == '_')
{
k++;
}
}
if (k == 0)
{
done = true;
}
return done;
}
it says subscript is out of range I need help to fix it
let me know how to fix it please its a project that is due very soon
that's all I got so far
Change:
for (size_t i = 0; i <= temp.length() - 1; i++)
to:
for (size_t i = 0; i <= letterGuessed.length() - 1; i++)