Why the randomize() function not working? - c++

I and my friend are trying to make a "Hangman" game using C++ for our school project. But on compilation, the messages show that the standard functions randomize() and random were not declared in this scope. What is wrong in the code?
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
const int MAXLENGTH=80;
const int MAX_TRIES=5;
const int MAXROW=7;
int letterFill (char guess, char secretword[], char guessword[]) {
int matches = 0;
for (int i = 0; secretword[i]!='\0'; i++) {
if (guess == guessword[i])
return 0;
if (guess == secretword[i]) {
guessword[i] = guess;
matches++;
}
}
return matches;
}
void initUnknown (char word[], char unknown[]) {
int i, length = strlen(word);
for (i = 0; i < length; i++)
unknown[i]='*';
unknown[i]='\0';
}
int main () {
char unknown [MAXLENGTH];
char letter;
int wrong_guesses=0;
char word[MAXLENGTH];
char words[][MAXLENGTH] = { "batman begins", "superman returns", "2012",
"tarzan", "goal", "300", "space jam", "transformers", "megamind",
"spiderman" };
randomize();
int n=random(10);
strcpy(word,words[n]);
initUnknown(word, unknown);
cout << "\n\nWelcome to hangman...Guess a Movie Name";
cout << "\n\nEach letter is represented by a star.";
cout << "\n\nYou have to type only one letter in one try";
cout << "\n\nYou have " << MAX_TRIES << " tries to try and guess the word.";
cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
while (wrong_guesses < MAX_TRIES) {
cout << "\n\n" << unknown;
cout << "\n\nGuess a letter: ";
cin >> letter;
if (!letterFill(letter, word, unknown)) {
cout << endl << "Whoops! That letter isn't in there!" << endl;
wrong_guesses++;
} else
cout << endl << "You found a letter! Isn't that exciting!" << endl;
cout << "You have " << MAX_TRIES - wrong_guesses;
cout << " guesses left." << endl;
if (!strcmp(word, unknown)) {
cout << word << endl;
cout << "Yeah! You got it!";
break;
}
}
if(wrong_guesses == MAX_TRIES) {
cout << "\nSorry, you lose...you've been hanged." << endl;
cout << "The word was : " << word << endl;
}
cin.get();
}

In C++ or C, you can use rand to generate random number. you can see more information at http://www.cplusplus.com/reference/cstdlib/rand/
regularly!

Use srand() to seed rand().
#include <cstdlib>
#include <cstddef>
#include <ctime>
...
int main(...){
...
srand(time(NULL));
int randomByte = rand()%256;
...
}

Related

My Ifstream reference is not working although it did in similar previous function

I have a file I want to continue calling on in different functions in my program. It worked fine as a reference in the shiftText function but when I repeated the reference in the next function, all that returns is 0,
Can I get a small hint at something I am missing perhaps to make it behave this way? Thanks!
(PS there's definitely a lot of 'fat' in this that I have included for testing purposes only)
I will eventually return the value of "e" into the shiftText function if you were curious why that's there :)
#include <iostream>
#include <cmath>
#include <fstream>
#include <cctype>
#include <string>
using namespace std;
void inputfile(ifstream &masterfile) // ask for file name
{
string filename;
cout << "Please enter the name and extension of your file " << endl;
cin >> filename;
masterfile.open(filename);
if (!masterfile)
{
cout << "warning: cannot open file" << endl;
exit(1);
}
}
int findShift(ifstream &file, int counter[]) // find most used char
{
char ch;
int code;
while (file.get(ch))
{
code = static_cast<int>(ch);
cout << code << " ";
counter[code]++;
}
int max, min;
int indexMax, indexMin;
max = counter[65];
indexMax = 65;
min = counter[65];
indexMin = 65;
for (int i = 66; i <= 122; i++)
{
if (counter[i] > max)
{
max = counter[i];
indexMax = i;
}
if (counter[i] < min)
{
min = counter[i];
indexMin = i;
}
}
cout << endl
<< "Most frequent was " << indexMax;
return indexMax;
}
void shiftText(ifstream &file) // this is where my program skips over my ifstream reference
{
char ch;
int code;
while (file.get(ch))
{
code = static_cast<int>(ch);
cout << code << " ";
}
}
char stopFlashing() // for sanity
{
char reply;
cout << endl
<< "Press q (or any other key) followed by 'Enter' to quit: ";
cin >> reply;
return 0;
}
int main()
{
int counter[256] = {0};
ifstream file;
inputfile(file);
int e = findShift(file, counter);
shiftText(file);
cout << endl << " " << file << " " << endl; // for testing, a zero is returned
stopFlashing();
}
In function findShift you loop over the file. In function shiftText you are trying to do the same. However, the file is already at its end. Before calling shiftText you should rewind the file by using seekg:
file.seekg(0, std::ios_base::beg)

looping back to start of do while loop [C++]

I need help for looping back on the start of the program [C++].
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
int rand_number = rand() % 101;
int number;
int counter = 1;
cout << "NUMBER GUESSING" << endl;
cout << "Try to guess number from 1 to 99: " << endl;
do
{
cout << "Input number: ";
cin >> number;
if (number < rand_number)
{
cout << "Number is too small." << endl;
}
else
{
if (number > rand_number)
{
cout << " Number is too big." << endl;
}
}
number++;
} while (number != rand_number);
cout << "Great! You guessed it in " << number << "th try." << endl;
cout << "Do you want to play again [Y/N]: ";
cin >> Y;
cin >> N;
// dont know how to proceed
return 0;
}
I need help for looping back on the start when it asks me if I want to play again and answer Yes "Y", if I answer No "N" it says Goodbye. Any help would be appreciated, Thanks.
Similar to how you are using a do while, try adding an outer while loop that checks if the N key was pressed
You could create a boolean playAgain which would start as true. If the player says no, set it to false. You can then put your do while in another do while(playAgain). This would loop the game until the player says he does not want to play again.
It is not the most orthodox method but it works :) Use goto.
int main()
{
mylabel:
...
if( <condition> )
{
goto mylabel;
}
...
}
If you want to have a more structured program write your main in anther function, say int func() and loop in main based on the return of the function.
int func()
{
...
if( <condition> )
{
return 1;
}
...
return 0;
}
int main()
{
while(func())
{};
return 0;
}
A very easy way to do this is to use nested while loops. You can use what you already have as the inner loop, then have another outside that that checks if the user has put in a Y or not. It can look something like this:
do {
do {
//Get numbers and check them
//...
} while(number != rand_number);
std::cout << "Some message" << std::endl;
std::cin >> option;
} while(option != 'N');
This goes through your loop, then allows the user to choose to continue. If they choose to go again, it will take them back up to the top of the outer while loop, and keep going until they say to stop.
EDIT:
Here would be the complete code:
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
char option = 'a';
do
{
int rand_number = rand() % 101;
int number;
int counter = 1;
std::cout << "NUMBER GUESSING" << std::endl;
std::cout << "Try to guess number from 1 to 99: " << std::endl;
do
{
std::cout << "Input number: ";
std::cin >> number;
if (number < rand_number)
{
std::cout << "Number is too small." << std::endl;
}
else if (number > rand_number)
{
std::cout << " Number is too big." << std::endl;
}
counter++;
} while (number != rand_number);
std::cout << "Great! You guessed it in " << counter << "th try." << std::endl;
std::cout << "Do you want to play again [Y/N]: ";
std::cin >> option;
} while(option !='N');
std::cout << "Goodbye!" << std::endl;
return 0;
}

Cannot get my getchar() function to work how I want it to work, output is10 not 2 c++

I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.
Main():
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int var, newvar;
cout << "enter a number:" << endl;
cin >> var;
newvar = getchar();
cout << newvar;
return 0;
}
Here is my output:
enter a number:
220
10
Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.
This is maybe not the cleanest way to do it but you can get every char one by one :
#include <iostream>
using namespace std;
int main()
{
int var;
cout << "enter a number:" << endl;
cin >> var;
std::string str = to_string(var);
for(int i=0; i < str.length();++i)
cout << str.c_str()[i] << endl;
return 0;
}
If you enter for example: "250e5" it will get only 250 and skip the last 5.
Edit:
This is just a simple parser and does not do any logic.
If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.
int main()
{
string str;
cout << "enter a number:" << endl;
cin >> str;
for(int i=0; i < str.length();++i) {
char c = str.c_str()[i];
if(c >= '0' && c <= '9') {
int number = c - '0';
cout << number << endl;
}
else if(c == '+') {
// do what you want with +
cout << "got a +" << endl;
} else if(c == '-')
{
// do what you want with -
cout << "got a -" << endl;
}
}
return 0;
}

String with character spacing

This program works EXCEPT that it does not allow a space between the first and last name. Below is an example as to what I am talking about:
Link to Picture
Can someone please help me to fix this? I believe it is in string playerName as it will not accept a space between the first and last name.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
// Structure to hold the Player Data
struct Player {
string playerName;
int playerNumber;
int pointsScored;
};
// Function Prototypes
void getPlayerInfo(Player &);
void showInfo(Player[], int);
int getTotalPoints(Player[], int);
void showHighest(Player[], int);
int main(int argc, char *argv[])
{
const int N = 12;
Player players[N];
for (int i = 0; i<N; i++) {
cout << "\nPLAYER #" << i + 1 << "\n";
cout << "---------\n";
getPlayerInfo(players[i]);
}
showInfo(players, N);
int totalPoints = getTotalPoints(players, N);
cout << "TOTAL POINTS: " << totalPoints << "\n";
cout << "The player who scored the most points is :";
showHighest(players, N);
cout << "\n";
system("pause");
return 0;
}
void getPlayerInfo(Player &P) {
cout << "Player Name:";
//cin >> P.playerName; **CHANGED THIS**
cin.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
std::getline(std::cin, P.playerName); **TO THIS**
do {
cout << "Player Number:";
cin >> P.playerNumber;
if (P.playerNumber<0)
cout << "invalid Input\n";
} while (P.playerNumber<0);
do {
cout << "Points Scored:";
cin >> P.pointsScored;
if (P.pointsScored<0)
cout << "invalid Input\n";
} while (P.pointsScored<0);
}
void showInfo(Player P[], int N) {
cout << "\nNAME" << "\t\tNUMBER" << "\t\tPOINTS SCORED" << "\n";
for (int i = 0; i<N; i++)
cout << P[i].playerName << "\t\t" << P[i].playerNumber << "\t\t" << P[i].pointsScored << "\n";
}
int getTotalPoints(Player P[], int N) {
int Points = 0;
for (int i = 0; i<N; i++)
Points += (P[i].pointsScored);
return Points;
}
void showHighest(Player P[], int N) {
int HighestPoint = P[0].pointsScored;
string Name = P[0].playerName;
for (int i = 1; i<N; i++) {
if (HighestPoint<P[i].pointsScored) {
HighestPoint = P[i].pointsScored;
Name = P[i].playerName;
}
}
cout << Name;
}
When std::cin uses operator>> to insert into a std::string, it stops reading at space (' ') characters. Use std::getline instead.
std::getline(std::cin, P.playerName); //read everything up to '\n'
The problem is in this code:
void getPlayerInfo(Player &P) {
cout << "Player Name:";
cin >> P.playerName;//<<----
cin treats ' ' (space) as a delimiter. If you want to have an input with ' ' (space) you need to use: (thanks to #James Root)
//before doing get line make sure input buffer is empty
see also: https://stackoverflow.com/a/10553849/3013996
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin,P.playerName);

C++ Hangman Swapping Underscores For Actual Chars

I am developing a Hangman game for an Uni assessment in C++ and I am having trouble displaying my hidden words after the user types a letter. So I have got the word being displayed as '_ _ _ _ _ _ _' but when I type a letter it doesn't swap the underscore for the actual letter.
game::game() {
words[0] = "strongly";
words[1] = "cheese";
words[2] = "computer";
words[3] = "coffee";
words[4] = "potatoes"; //words that can be in the game
words[5] = "zebra";
words[6] = "extinguisher";
words[7] = "solution";
words[8] = "diligent";
words[9] = "flabbergasted";
numGuesses = 0;
hiddenWord = words[rand() % 10]; //pick a random word from array words
completedWord = hiddenWord;
//for loop for changing the word to underscores
for (int i = 0; i < completedWord.length(); i++) {
completedWord[i] = '_';
}
//for loop adding a space after underscore
for (int i = 0; i < completedWord.length(); i++) {
cout << completedWord[i] << " ";
}
cout << endl;
cout << "Please enter a letter: ";
char guessedLetter;
cin >> guessedLetter;
if (guessedLetter = completedWord[0]) {
completedWord = guessedLetter;
//cout << guessedLetter << endl;
cout << completedWord << endl;
}
}
My whole program is separated into different header files and cpp files. So the code above is from my gameguesses.cpp and the header for that is below:
class game {
public:
string words[10];
game();
string hiddenWord;
int numGuesses;
string completedWord;
};
And this is what I actually get:
A help would be appreciated. Thank you!
I see 2 issues:
if (guessedLetter = completedWord[0])
That line needs == not =.
Secondly, you are comparing the guess only to the first letter of the hidden word. You need to write a loop to check each letter and substitute where it matches the guess, not just in element [0].
See if this helps.
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
#include <locale>
using namespace std;
class Game
{
public:
Game()
{
gameDictionary.push_back("strongly");
gameDictionary.push_back("cheese");
gameDictionary.push_back("computer");
gameDictionary.push_back("coffee");
gameDictionary.push_back("potatoes");
gameDictionary.push_back("zebra");
gameDictionary.push_back("extinguisher");
gameDictionary.push_back("solution");
gameDictionary.push_back("diligent");
gameDictionary.push_back("flabbergasted");
}
// Play until winning or losing. Returns true on win, false on loss.
bool playGame()
{
numGoodGuesses = 0;
numBadGuesses = 0;
numWordLettersFound = 0;
hiddenWord = gameDictionary[rand() % gameDictionary.size()]; //pick a random word from array words
guessedWordTracker = hiddenWord;
for (string::size_type i = 0; i < hiddenWord.size(); i++)
{
completedWord += "_ ";
}
for (;;)
{
cout << completedWord << endl;
cout << "Please enter a letter: ";
char guessedLetter;
do
{
cin >> guessedLetter;
guessedLetter = tolower(guessedLetter);
if (!isalpha(guessedLetter))
{
cout << "Invalid letter, try again." << endl;
}
} while (!isalpha(guessedLetter));
string::size_type pos;
int numMatchesFoundThisTime = 0;
while ((pos = guessedWordTracker.find_first_of(guessedLetter)) != string::npos)
{
completedWord[pos * 2] = guessedWordTracker[pos];
guessedWordTracker[pos] = '\x01';
numMatchesFoundThisTime++;
}
numWordLettersFound += numMatchesFoundThisTime;
if (numMatchesFoundThisTime > 0)
{
numGoodGuesses++;
cout << "Wow, you found " << numMatchesFoundThisTime
<< (numMatchesFoundThisTime > 1 ? " letters!" : " letter!")
<< endl;
if (numWordLettersFound == hiddenWord.size())
{
cout << "Congrats... the word is '" << hiddenWord << "' ... great job!" << endl;
return true;
}
}
else
{
numBadGuesses++;
cout << "Sorry, the letter '" << guessedLetter << "' is not in the word." << endl;
}
int totalGuesses = numGoodGuesses + numBadGuesses;
cout << "You've made " << numGoodGuesses << " good guesses, "
<< numBadGuesses << " bad guesses, "
<< totalGuesses << " total guesses." << endl;
// Example failure:
const int BAD_GUESSES_ALLOWED = 30;
if (numBadGuesses > BAD_GUESSES_ALLOWED)
{
cout << "Sorry, you have no more guesses left. You lose." << endl;
return false;
}
}
}
private:
vector<string> gameDictionary;
string hiddenWord;
string guessedWordTracker;
string completedWord;
int numGoodGuesses;
int numBadGuesses;
int numWordLettersFound;
};
int _tmain(int argc, _TCHAR* argv[])
{
Game g;
g.playGame();
return 0;
}