Hi, below is part of my code for a simple Hangman Program which generates a random number and selects the word from a text file. This word is put in a string word. I apply the word.c_str (); feature to convert it from a string to a char array but to pass it to an array I had to create a new char array s[20] = {0}; and assign each element of the previous char array to the elements of s. What am I doing wrong. Is there a way of going around it without having to create all those arrays? Attached is the whole program.
// function prototype
string& someThingToDo(string &inString); // this is for c++ style strings..
// for a char[20] pass I might do something like this
char* someThingtoDo(char *pString); // this will take any char[] size
// it also might be expecting a string with a null last character type.
// I might call this like
char myString[20];
someThingtoDo(&myString[0]);
Another thing I don't understand why I am doing things like this. Why not just use the std::string for everything?
std::string guessWord;
std::string matchWord;
std::string shieldedWord;
ifstream f(selc); // hmm I am not checking to see if the file was good...
for(int w = 0; w < iSecret; w++)
{
getline(f, matchWord);
//fseek(0, 12);
}
f.close();
// astrisk the word
// using shielded word I will assign '*' to it for the length of the match word.
shieldedWord.assign("*", matchWord.length() );
std::cout << "Please Make a guess:" << std::endl;
std::cin >> guessWord;
if(guessWord == MatchWord)
{
std::cout << "You match the word" << std::endl;
}
else
{
if(guessWord.length() == 1)
{
bool bFound = false;
char searchChar = guessWord[0];
// search the match string for the searchChar
for(int nIndex = 0; nIndex < MatchWord.length(); nIndex++)
{
// at each time I find the search character
// I want to update the shieldedWord for that character
// and I want to know if I found anything.
if(matchWord[nIndex] == searchChar)
{
bFound = true;
shieldedWord[nIndex] = searchChar;
}
}
if(bFound == true)
{
std::cout << "You Matched " << searchChar << " in the word." << std::endl;
}
else
{
std::cout << "You did not match any letter in the word." << std::end;
std::cout << "Sadly, you rope is getting shorter" << std::endl;
}
}
else // else guessWord > 1 in length.
{
std::cout << "I am sorry that wasn't the word." << std::endl;
std::cout << "Sadly, you rope is getting shorter" << std::endl;
}
} // end the else on guessWord equaling matchWord