Advertisement
ivelins93

Untitled

Jan 23rd, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <fstream>
  4. #include <ctime>
  5. #include <string>
  6. using namespace std;
  7. const int TRIES = 5;
  8. int letterFill(char, string, string&);
  9. int main()
  10. {
  11.  
  12.  
  13.  
  14. string name;
  15. char letter;
  16. int num_of_wrong_guesses = 0;
  17. string word;
  18. string words[5000];
  19. string line;
  20. ifstreammyfile("words.txt");
  21. if (myfile.is_open())
  22. {
  23. int index = 0;
  24. while (getline(myfile, line))
  25. {
  26. words[index] = line;
  27. index++;
  28. }
  29. myfile.close();
  30. }
  31. else cout<< "Unable to open file";
  32. //choose and copy a word from array of words randomly
  33. int n = rand() % 10;
  34. word = words[n];
  35. // Initialize the secret word with the * character.
  36. string unknown(word.length(), '*');
  37. // welcome the user
  38. cout<< "\n\nWelcome to hangman!! Guess the word";
  39. cout<< "\n\nYou have to type only one letter in one try.";
  40. cout<< "\n\nYou have " << TRIES << " tries to try and guess the word.";
  41. cout<< "\n*****************************************";
  42. // Loop until the guesses are used up
  43. while (num_of_wrong_guesses< TRIES)
  44. {
  45. cout<< "\n\n" << unknown;
  46. cout<< "\n\nGuess a letter: ";
  47. cin>> letter;
  48. if (letterFill(letter, word, unknown) == 0)
  49. {
  50. cout<<endl<< "Whoops! That letter isn't in there!" <<endl;
  51. num_of_wrong_guesses++;
  52. }
  53. else
  54. {
  55. cout<<endl<< "You found a letter!" <<endl;
  56. }
  57. // Tell user how many guesses has left.
  58. cout<< "You have " << TRIES - num_of_wrong_guesses;
  59. cout<< " guesses left." <<endl;
  60. // Check if user guessed the word.
  61. if (word == unknown)
  62. {
  63. cout<< word <<endl;
  64. cout<< "Yeah! You got it!";
  65. break;
  66. }
  67. }
  68. if (num_of_wrong_guesses == TRIES)
  69. {
  70. cout<< "\nSorry, you lose." <<endl;
  71. cout<< "The word was : " << word <<endl;
  72. }
  73. cin.ignore();
  74. cin.get();
  75.  
  76. return 0;
  77. }
  78. int letterFill(char guess, string secretword, string &guessword)
  79. {
  80. int i;
  81. int matches = 0;
  82. int len = secretword.length();
  83. for (i = 0; i<len; i++)
  84. {
  85. if (guess == guessword[i])
  86. return 0;
  87. if (guess == secretword[i])
  88. {
  89. guessword[i] = guess;
  90. matches++;
  91. }
  92. }
  93. return matches;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement