I just got started with C++ and I'm currently trying to build an algorith that cracks passwords. I ran into a problem with nested loops for longer passwords. It currently works fine for 4 character passwords, I have to wait for a while, but it works. Is there a way to get rid of the hard coded nested loops, to make the algorithm work for more than for characters without having to copy and paste the if statements over and over again?
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
const char alphanum[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%^&* ";
const string pw = "0000";
bool cracked = false;
int tries = 0;
const int pwLength = pw.length();
string crack();
string guess="0";
const int maxLen = 30;
int main()
{
clock_t begin, end;
double time;
begin = clock();
string crackedPassword = crack();
end = clock();
time = double(end - begin) / (double)CLOCKS_PER_SEC;
cout << "The password is: " << crackedPassword << " The program checked a total of " << tries << " possibilites and took " << time << " seconds to crack the password!";
return 0;
}
string crack() {
int index = 0;
int repeat = 0;
while (!cracked) {
for (int i = 0; i < 71; i++) {
tries++;
guess[index] = alphanum[i];
cout << "Trying: " << guess << endl;
if (repeat > 0) {
for (int i = 0; i < 71; i++) {
tries++;
guess.push_back(alphanum[i]);
cout << "Trying: " << guess << endl;
if (repeat > 1) {
for (int i = 0; i < 71; i++) {
tries++;
guess.push_back(alphanum[i]);
cout << "Trying: " << guess << endl;
if (repeat > 2) {
for (int i = 0; i < 71; i++) {
tries++;
guess.push_back(alphanum[i]);
cout << "Trying: " << guess << endl;
if (guess == pw) {
cracked = true;
break;
}
else {
guess.pop_back();
}
}
}
if (guess == pw) {
cracked = true;
break;
}
else {
guess.pop_back();
}
}
}
if (guess == pw) {
cracked = true;
break;
}
else {
guess.pop_back();
}
}
}
if (guess == pw) {
cracked = true;
break;
}
}
repeat++;
}
return guess;
}
Related
I'm unable to get invalid emails to print in my code. I'm able to call the student roster just fine but that's about it.
#include <iostream>
#include <string>
#include "student.h"
#include "degree.h"
#include "roster.h"
using namespace std;
int main()
{
const string studentData[] =
{
"A1,John,Smith,John1989#gm ail.com,20,30,35,40,SECURITY",
"A2,Suzan,Erickson,Erickson_1990#gmailcom,19,50,30,40,NETWORK",
"A3,Jack,Napoli,The_lawyer99yahoo.com,19,20,40,33,SOFTWARE",
"A4,Erin,Black,Erin.black#comcast.net,22,50,58,40,SECURITY",
};
Roster* classRoster = new Roster(numberOfStudents);
for (int i = 0; i < numberOfStudents; ++i)
{
cout << studentData[i] << "," << endl;
}
cout << endl;
cout << "Invalid emails:";
for (int i = 0; i < numberOfStudents; ++i)
{
classRoster->printInvalidEmails();
}
cout << "Average days per class for each student" << endl;
for (int i = 0; i < numberOfStudents; ++i)
{
cout << endl;
}
cout << endl;
classRoster->printByDegreeProgram();
cout << endl;
system("pause");
return 0;
}
Here is my roster.cpp
#include <iostream>
#include <string>
#include "student.h"
#include "degree.h"
#include "roster.h"
using namespace std;
Roster::Roster()
{
This->rosterSize = 0;
this->lastIndex = -1;
this->classRosterArray = nullptr;
}
Roster::Roster(int rosterSize)
{
this->rosterSize = rosterSize;
this->lastIndex = -1;
this->classRosterArray = new Student * [rosterSize];
}
void Roster::add(string studentId, string firstName, string lastName,
string
emailAddress, int age,
int daysInCourse1, int daysInCourse2, int daysInCourse3, Degree degree)
{
}
void Roster::remove(string studentId)
{
for (int i = 0; i <= lastIndex; ++i)
{
if (classRosterArray[i] == nullptr)
{
cout << "ERROR: Student with ID: " << studentId << " not found" <<
endl;
break;
}
else if (studentId == classRosterArray[i]->getStudentId())
{
classRosterArray[i] = nullptr;
cout << "Student removed" << endl;
}
}
}
void Roster::printAll()
{
for (int i = 0; i <= this->lastIndex; ++i)
{
(this->classRosterArray)[i]->print();
}
}
void Roster::printAverageDaysInCourse(string studentId)
{
bool found = false;
for (int i = 0; i <= lastIndex; ++i) {
if ((*classRosterArray[i]).getStudentId() == studentId) {
found = true;
int average = 0;
average = (classRosterArray[i]->getNumberOfDaysToCompleteCourse()
[0]
+ classRosterArray[i]->getNumberOfDaysToCompleteCourse()[1] +
classRosterArray[i]->getNumberOfDaysToCompleteCourse()[2]) /
3;
cout << "Average days it took student " << studentId << " to
complete
a course: " << average
<< " days" << endl;
}
}
if (!found) cout << "Student not found." << endl;
}
void Roster::printInvalidEmails()
{
for (int i = 0; i < numberOfStudents; ++i)
{
string email = classRosterArray[i]->getEmailAddress();
bool isBad = false;
size_t at = email.find("#");
size_t period = email.find(".");
if (at == string::npos)
{
cout << "Invalid email. Missing # symbol." << endl;
}
else if (period == string::npos)
{
cout << "Invalid email. Missing a period." << endl;
}
else if (email.find(" ") != string::npos)
{
cout << "Invalid email. Spaces not allowed." << endl;
}
}
}
void Roster::printByDegreeProgram()
{
for (int i = 0; i < degreeType; ++i)
{
cout << &Roster::printByDegreeProgram;
}
}
Roster::~Roster()
{
for (int i = 0; i < numberOfStudents; ++i)
{
delete classRosterArray[i];
}
}
I'm just starting out and am not sure if i've totally messed myself up. Any help would be greatly appreciated. I thought might have been able to figure it out and i've tried a few different times but still unable to correct.
I am trying to create an algorithm for bruteForce cracking MD5 hash.
My goal is to measure the time consumption when splitting into fibers for the processor and optionally graphics in compute clastr.
I got stuck in creating an algorithm.
The input should be a string. According to the number of string characters, I need to create the same number of forcycles.
Statically written for 3 digist, it looks like this:
#include <iostream>
#include <string>
#include "md5.h"
using namespace std;
int main()
{
string imput = "slv";
cout << "imput string: "<< imput << endl;
cout << "MD5 HASH: "<< wantedHash << endl;
do
{
cout << '\n' << "Enable BruteForce Craker";
} while (cin.get() != '\n');
string s;
for(int i=0; i != 256; i++)
{
for(int j=0; j != 256; j++)
{
for(int k=0; k != 256; k++)
{
string s = md5(string(1,(char)i) + string(1,(char)j) + string(1,(char)k));
serchCounter++;
if(s == wantedHash)
{
cout << "Find: " << string(1,(char)i) + string(1,(char)j) + string(1,(char)k) << endl;
cout << "Count TestedHash: " << serchCounter << endl;
return 0;
}
}
}
}
return 0;
}
My idea .. something like that ...
#include <iostream>
#include <string>
#include "md5.h"
using namespace std;
string imput = "s";
string wantedHash = md5(imput);
double serchCounter = 0;
int bruteForse(int longString, string s)
{
for(int i=0; i != 256; i++)
{
string s = md5(string(1,(char)i));
serchCounter++;
if(s == wantedHash)
{
cout << "Find: " << string(1,(char)i);
cout << "Count TestedHash: " << serchCounter << endl;
return 0;
}
}
if(longString > 1) bruteForse(--longString, s);
return 0;
}
int main()
{
cout << "imput string: "<< imput << endl;
cout << "MD5 HASH: "<< wantedHash << endl;
bruteForse(imput.length(),imput);
}
I would do:
bool increase(std::string& s)
{
for (auto rit = s.rbegin(); rit != s.rend(); ++rit) {
auto& c = s[i];
if (c == -1) {
c = 0;
continue;
} else if (c == 127) {
c = -128;
} else {
++c;
}
return true;
}
return false;
}
void bruteForce(std::size_t size, const string& wantedHash)
{
std::string s;
s.resize(size);
do {
if (md5(s) == wantedHash) {
cout << "Find: " << s << std::endl;
}
} while (increase(s));
}
Basically I've been playing a little with C++ and I am doing an exercise from this website called "Graduation".
So far I've been doing good for a beginner but here's my first problem which I have been struggling for the last hours and I can't find a solution online.
I am using 2 strings of arrays, one 80x80 for the map and one 100x20 for all the existing bunnies. I am putting all the data together in one string like SEX|COLOR|AGE|COORDINATES|NAME. So to extract each piece of the grid I always use 2 for functions to run throughout all the array and cut for example the 2nd character so I can know the color of each bunny in the array.
It worked fine when I used it to discover the sex of each bunny in the array but I am trying to do the same for the color and it isn't working. My program keeps crashing with the error screen I left in the screenshot I uploaded.
Heres the code:
Main.cpp
#include <iostream>
#include "Add.h"
#include "GetNames.h"
#include <string>
#include "PlaceOnMap.h"
#include "Colours.h"
using namespace std;
int start = 1;
int main()
{
while (start == 1)
{
Add(5);
PlaceOnMap(bunniestotal);
Colour();
start = 0;
}
system("pause");
return 0;
}
Add.h
#pragma once
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string>
#include <windows.h>
#include "GetNames.h"
using namespace std;
int colours;
int cB, rB;
int bunnies = 0;
int bunniestotal = 0;
int sex = 0;
int h = 0;
string listB[10][100];
void Add(int x)
{
srand(time(NULL));
/***********************************************************************************************/
while (h < 1) {
for (int rB = 0; rB < 10; rB++) //DO THE SLOTS FOR THE BUNNIES
{
for (int cB = 0; cB < 100; cB++)
{
listB[rB][cB] = "-";
}
}
h = 1;
}
/***********************************************************************************************/
while (bunnies < x) //CHOOSE RANDOM SLOTS FOR BUNNIES
{
rB = rand() % 10;
cB = rand() % 100;
if (listB[rB][cB] == "-")
{
listB[rB][cB] = "B";
bunnies++;
}
}
bunniestotal = bunniestotal + bunnies;
bunnies = 0;
/***********************************************************************************************/
for (int rB = 0; rB < 10; rB++) //SET SEX AND COLOUR
{
for (int cB = 0; cB < 100; cB++)
{
if (listB[rB][cB] == "B")
{
sex = rand() % 2 + 1;
//cout << sex << endl;
if (sex == 1)
{
colours = rand() % 4 + 1;
switch (colours)
{
case 1: listB[rB][cB] = "mR";
break;
case 2: listB[rB][cB] = "mY";
break;
case 3: listB[rB][cB] = "mC";
break;
case 4: listB[rB][cB] = "mB";
break;
}
listB[rB][cB] = listB[rB][cB] + "0";
//cut = listB[rB][cB].substr(0, 1);
//cout << listB[rB][cB] << "Cut - " << cut << endl;
//listB[rB][cB] = listB[rB][cB] + GetNames("M") + " ";
//cout << listB[rB][cB] << endl;
//listB[rB][cB] = listB[rB][cB] + GetNames("M");
//cout << listB[rB][cB] << endl;
}
else if (sex == 2)
{
colours = rand() % 4 + 1;
switch (colours)
{
case 1: listB[rB][cB] = "fR";
break;
case 2: listB[rB][cB] = "fY";
break;
case 3: listB[rB][cB] = "fC";
break;
case 4: listB[rB][cB] = "fB";
break;
}
listB[rB][cB] = listB[rB][cB] + "0";
//cut = listB[rB][cB].substr(0, 1);
//cout << listB[rB][cB] << "Cut - " << cut << endl;
//cout << rB << " " << cB << endl;
//listB[rB][cB] = listB[rB][cB]+GetNames("F") + " ";
//cout << listB[rB][cB] << endl;
//listB[rB][cB] = listB[rB][cB] + GetNames("F");
//cout << listB[rB][cB] << endl;
}
}
}
}
}
PlaceOnMap.h
#pragma once
#include <iostream>
#include "Add.h"
#include <string>
#include <sstream>
#include <Windows.h>
#include "Colours.h"
using namespace std;
string map[80][80];
string cut;
ostringstream join;
ostringstream join1;
int xB, yB;
int hh = 0;
int capslock;
int y = 0;
int z = 0;
int u, o;
void PlaceOnMap(int bunniesn)
{
HANDLE color = GetStdHandle(STD_OUTPUT_HANDLE);
//cout << "PlaceOnMap " << listB[rB][cB] << endl;
//cout << rB << " " << cB << endl;
//cut = listB[rB][cB].substr(0, 1);
//cout << cut << endl;
/***********************************************************/
while (hh < 1)
{
for (int xB = 0; xB < 80; xB++) // CREATE MAP
{
for (int yB = 0; yB < 80; yB++)
{
map[xB][yB] = "-";
}
}
hh = 1;
}
/***********************************************************/
//cout << bunniesn << endl;
//cout << rB << endl;
//cout << cB << endl;
for (y = 0; y < 10; y++)
{
for (z = 0; z < 100; z++)
{
nextone:
if (listB[y][z].length() < 4) //DOESN'T LET BUNNIES THAT ARE ALREADY PLACED ENTER THIS LOOP
{
//cout << y << " " << z << endl;
cut = listB[y][z].substr(0, 1); //CUTS THE STRING IN ORDER TO KNOW IF IT IS A FEMALE OR A MALE
if (cut == "f" || cut == "m")
{
if (cut == "f")
{
capslock = 1;
}
else if (cut == "m")
{
capslock = 2;
}
generate:
xB = rand() % 80;
yB = rand() % 80;
if (map[xB][yB] == "-")
{
//cout << "Found a slot!" << endl;
//Sleep(2000);
//join << xB;
//join1 << yB;
listB[y][z] += to_string(xB);
listB[y][z] += to_string(yB);
//cout << "Size - " << listB[y][z].length() << endl;
if (listB[y][z].length() == 5)
{
listB[y][z] = listB[y][z] + " ";
listB[y][z] = listB[y][z] + " ";
}
else if (listB[y][z].length() == 6)
{
listB[y][z] = listB[y][z] + " ";
}
cout << listB[y][z] << endl;
//Sleep(6000);
if (capslock == 1)
{
map[xB][yB] = "f";
}
else if (capslock == 2)
{
map[xB][yB] = "m";
}
z++;
x++;
//cout << x << endl;
//Sleep(3000);
if (x < bunniesn)
{
goto nextone;
}
else
{
goto done;
}
}
else
{
goto generate;
}
}
}
}
}
done:
cout << "All done" << endl;
SetConsoleTextAttribute(color, 15);
}
Colours.h (Where the problem is happening!!)
#pragma once
#include <iostream>
#include "PlaceOnMap.h"
#include <string>
#include "Add.h"
using namespace std;
string wordString;
int t, r;
void Colour()
{
for (t = 0; t < 20; t++)
{
for (r = 0; r < 100; r++)
{
wordString = listB[t][r].substr(1, 2); //CUTS THE STRING IN ORDER TO KNOW ITS COLOR
//cout << wordString << " ";
if (wordString == "R")
{
cout << "GOT RED" << endl;
}
else if (wordString == "C")
{
cout << "GOT CYAN" << endl;
}
else if (wordString == "B")
{
cout << "GOT BLUE" << endl;
}
else if (wordString == "Y")
{
cout << "GOT YELLOW" << endl;
}
}
cout << endl;
}
}
If it is something really dumb I am sorry! Kinda noob but just trying to learn more and more! :) If you need any more info feel free to ask for!
Thank you.
In Colours.h, change for (t = 0; t < 20; t++) to for (t = 0; t < 10; t++). You only have 10 subarrays allocated, so you were going outside the bounds of the array.
From quickly looking through your code:
You defined:
string listB[10][100];
And you iterate the first index up to 20 in Colours.h:
for (t = 0; t < 20; t++)
Which works for:
listB[0][r];
listB[1][r];
listB[2][r];
listB[3][r];
listB[4][r];
listB[5][r];
listB[6][r];
listB[7][r];
listB[8][r];
listB[9][r];
And then you try accessing
listB[10][r]
which is the 11th index and not allocated.
If you redefined it somewhere and I missed I am sorry.
List.cpp (class definitions)
I have been working on code that is suppose to help familiarize with classes. My code currently has a function that displays a menu of options for the users. Option [1] is suppose to add a string, option [2] is suppose to remove a string from the list, option [3] prints the string list, option [4] exits. My option [1] seems to work okay as the user is able to input one string at a time but I am having a hard time with the removal of a string. The strings are currently stored in an array of 10 elements. I believe the function I wrote for the string removal is okay as I have debugged it and it seems successful, however, I am not seeing results on my console window.
My array is located in a private class in my class: string items[MAX_ITEMS]; along with another variable called: int totalItems;
The class is then called in my main function using a switch case:
//This code snippet below is located in a separate cpp file with main
cout << "Please enter the text you want to remove: " << endl;
cin >> userInput;
list1.remove(userInput);
////////////////////////////////////////////////////////////////////
//preprocessor directives
#include <iostream>
#include <string>
//header files
#include "list.h"
using namespace std;
List::List()
{
//clear array prior to starting (set everything to NULL)
for (int i = 0; i < MAX_ITEMS; i++)
{
items[i] = " ";
}
totalItems = 0;
}
//void List::init()
//{
// string items[MAX_ITEMS];
// totalItems = 0;
//}
bool List::insert(const string& data)
{
//verifies that string is not empty, not in the list, and not full
if (data.empty() == true || inList(data) == true || isFull() == true)
{
return false;
}
else
{
// items[isFull)] = data;
// totalItems++;
items[totalItems++] = data;
return true;
}
}
bool List::isEmpty() const
{
//runs through loop to verify array is empty
for (int i = 0; i < MAX_ITEMS; i++)
{
if (items[i].empty() != true)
{
return false;
}
}
return true;
}
//identifies whether the string is full or not
bool List::isFull() const
{
if (totalItems == MAX_ITEMS)
{
return true;
}
else
{
return false;
}
}
//identifies whether the string is already in the list or not
bool List::inList(const string& theList)
{
for (int i = 0; i < MAX_ITEMS; i++)
{
if (items[i] == theList)
{
return true;
}
}
return false;
}
bool List::remove(const string& data)
{
if (inList(data) == true || data.empty() == true)
{
return false;
}
for (int i = 0; i < MAX_ITEMS; i++)
{
if (items[i] == data)
{
items[i] == " ";
for (int j = i; j < MAX_ITEMS; j++)
{
items[j] = items[j + 1];
items[MAX_ITEMS - 1] == " ";
break;
}
}
}
totalItems--;
return true;
}
//prints list
void List::printList()
{
for (int i = 0; i < MAX_ITEMS; i++)
{
cout << i << items[i] << '\t';
}
}
list_test.cpp (main.cpp)
#include <iostream>
#include <string>
//header files
#include "list.h"
using namespace std;
//function prototypes
int showSelection();
int main()
{
List list1;
string userInput = "";
int userChoice;
// list1.init();
userChoice = showSelection();
while (userChoice != 4)
{
switch(userChoice)
{
case 1:
cout << "Please enter the text you want to add: " << endl;
cin >> userInput;
list1.insert(userInput);
/*if (list1.inList(userInput) == false)
{
cout << "Text is already entered in the list!" << endl;
}*/
if (list1.isFull() == true)
{
cout << "You have entered the MAXIMUM amount of elements!" << endl;
}
break;
case 2:
cout << "Please enter the text you want to remove: " << endl;
cin >> userInput;
list1.remove(userInput);
break;
case 3:
cout << "Printed list: " << endl;
list1.printList();
break;
}
userChoice = showSelection();
}
cout << "Goodbye. Please press enter to exit." << endl;
//TESTING PURPOSES FOR FUNCTIONS
cout << list1.insert(userInput) << endl;
cout << list1.isEmpty() << endl;
cout << list1.isFull() << endl;
cout << list1.inList(userInput) << endl;
return 0;
}
/* ===========================================
Name: showSelection
Desc: displays menu for user to choose options
for their inputted string(s).
Args: none
Retn: none
=========================================== */
int showSelection()
{
int userChoice;
bool exit = false;
while (exit == false)
{
cout << "\nTo select an option, please enter the corresponding number: " << endl;
cout << "[1] to add a string" << endl;
cout << "[2] to remove a string" << endl;
cout << "[3] to print a string" << endl;
cout << "[4] to exit" << endl << endl;
cin >> userChoice;
cout << "You entered option: " << userChoice << endl;
cout << '\n';
if (userChoice == 1 || userChoice == 2 || userChoice == 3 || userChoice == 4)
{
exit = true;
}
else
{
cout << "Invalid selection" << endl;
}
}`enter code here`
return userChoice;
}
Here is how you code should probably look:
bool List::remove(const string& data) {
// only check if the list is empty so you don't nececarily go through it
// you shoudn't ask here if the given string is in the list
// because you will search for it anyway just below
if (data.empty())
return false;
for (int i = 0; i < MAX_ITEMS; ++i) {
if (items[i] == data) { // now if it was found
items[i] = " "; // set it to your empty value
--totalItems; // prefix -- is faster then postfix one (no copy is created)
for (int j = i; j < MAX_ITEMS - 1; ++j) {
// stop at j < MAX_ITEMS - 1 because you wouldn't want
// to swap last element with the next because there
// is none behind it
if (items[j + 1] == " ")
// if the next item is already empty you don't need to shift any more
return true;
// swap the next item with much more
// efficient std::swap function
std::swap(items[j], items[j + 1]);
}
return true; // value is removed and items shifted so you can now return
}
}
// if function gets to this point that means the value wasn't found
return false;
}
If you would like to make your code more efficient, I can give you more suggestions on how to do it. This above should answer your question.
Also using an array for a struct like this isn't optimal at all. Using linked listed would mean no shifting would be required.
Edit: replaced long text with a code example
Edit2: added return statement if shifting is no longer necessary
FOR me it's unclear what you want to do as unavailability of full code to run.
But I think this should work as of what I think yo want to do
bool List::remove(const string& data){
for (int i = 0; i < totalItems; i++)
{
if (items[i] == data)
{
for (int j = i; j < totalItems-1; j++)
{
items[j] = items[j+1];
}
totalItems--;
return true;
}
}
return false;
if (inList(data) == true || data.empty() == true)
{
return false;
}
If the data parameter is in your list object, you return without removing anything? this should be !inList(data)
Additionally, when you make it into the loop below this code this loop:
for (int j = i; j < MAX_ITEMS; j++)
{
items[j] = items[j + 1];
items[MAX_ITEMS - 1] == " ";
break;
}
will only execute for j=i, the "break" statement will stop execution of this inner loop, and go back to the outer loop.
EDIT: this is how I personally would go about this problem.
bool List::remove(const string& data)
{
bool retVal;
if (!inList(data) || data.empty())
{
retVal = false;
}
else{
for (int i = 0; i < MAX_ITEMS; i++)
{
if (items[i] == data)
{
items[i] = " ";
for (int j = i; j < (MAX_ITEMS - 1); j++)
{
items[j] = items[j + 1];
}
items[MAX_ITEMS-1] = " ";
}
}
totalItems--;
retVal = true;
}
return retVal;
}
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++)