hangman game help

How would I get the number of dashes to be the same length as the word the user is trying to guess? Right now its a set length that I declare at the beginning.

word.txt:

blue

love

basketball

orange

texas

football

usa

light

shirt

game

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
  #include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

string getWord()
{
  int count = 0;
  string wordList[10];
  ifstream fin;
  fin.open("word.txt");
  if(!fin)
  {
    cout << "Could bot open file" << endl;
  }
  int i =0;
  while(fin >> wordList[i])
  {
    i++;
  }
  srand(time(0));

  string ranWord = wordList[rand() % 10];

  return ranWord;
}

int main()
{
  //cout << "Love" << endl;
  //string word = "loving";
  
  string dashes = "----------";
  string word = getWord();
  //string dashes = "-";
  

  //string word = getWord();

  int guessesLeft = word.size();
  bool correctGuess = false;
  bool finalAnswer = true;
  
  char userGuess;

  do {
      cout << dashes << endl;
      correctGuess = false;
      finalAnswer = true;
      cout << "Guess: ";
      cin >> userGuess;

      for(int i = 0; i < word.size(); i++) { 
        if (word[i] == userGuess) {
            cout << "Correct guess!" << endl;
            dashes[i] = userGuess;
            word[i] = 'R';
            correctGuess = true;
        }
    } 
    if (correctGuess == false) 
    { 
        cout << "Incorrect guess" << endl;
        guessesLeft--;
    }
    for (int i = 0; i < word.size(); ++i) {
        if (word[i] != 'R') finalAnswer = false;
    }
    
    if (finalAnswer) {
        cout << "You guessed everything correctly " << endl;
    }
  } while (guessesLeft != 0); 
  cout << "Too many incorrect guesses" << endl;
  cout << word << endl;
  return 0;
}
Probably many ways.

But
1
2
3
  string dashes = "";
  string word = getWord();
  for ( size_t i = 0 ; i < word.size() ; i++ ) dashes += "-";
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main()
{
    std::string word{"basketball"};
    
    std::string spaces{""};
    spaces.insert(0,word.length(),'-');
    
    std::cout << word << '\n';
    std::cout << spaces << '\n';
    
    return 0;
}
Don't define dashes until after you set the word. Then use the fill constructor:
1
2
3
...
word = getWord();
string dashes(word.size(), '-');

See the "fill" constructor here:
http://www.cplusplus.com/reference/string/string/string/
That's a better way
Topic archived. No new replies allowed.