I am writing a hangman program for class and so far I am able to read in and randomly pick a word from the file. The problem I am facing is counting the number of letters in the chosen word. Once I get that I can work on the rest of the program. The reason for the count is once the game starts, I will choose the word, count the letters and display a number of asterisks or some other character to represent the letters in the word......as the user guesses the letters, i will replace the character with the letter until they win (or lose) code is as follows
//Hangman in C++
//Patrick Nealey
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <ctime>
const int MAX_WORDS = 100;
using namespace std;
int loadArray (string words [MAX_WORDS]);
string randomword (int wordCount, string words[MAX_WORDS]);
int main()
{
string words[MAX_WORDS];
int wordCount;
string word;
cout <<"Welcome to Hangman...Don't lose your head!"<<endl;
ifstream infile ("words.txt");
if(!infile)
{
cerr <<"Could not open input file";
return -1;
}
wordCount = loadArray(words); //call load file and count words;
randomword (wordCount, words);
return 0;
}
int loadArray (string words [MAX_WORDS])
{
// open the data file - abort the program if file not found
ifstream infile;
infile.open ("words.txt");
if (!infile)
{
cerr << "Cannot open words file.txt\n";
exit (1);
}
// input all the words up to limit total and count
int i = 0;
getline (infile, words[i]); //load first line
while (i < MAX_WORDS && infile)
{
i++;
getline (infile, words[i]); //load next line
}
if (i == MAX_WORDS && infile >> ws && infile.good())
{ // too many word check
cerr << "Error: too many words\n";
infile.close ();
exit (2);
}
else if (!infile.eof() && infile.fail())
{ // bad data check
cerr << "Error: bad data in the file\n";
infile.close ();
exit (3);
}
infile.close ();
return i; //return count of words
}
string randomword (int wordCount, string words[MAX_WORDS])
{
string word;
ifstream infile ( "words.txt" );
srand((unsigned)time(0));
int c;
c = (rand()%wordCount)+1;
do
infile >> word;
while ( --c >= 0 );
return word;
}