For loop error

I am getting a segmentation error and the core gets dumped when the for loop is run. I know it's because I have a dangling variable (letterInputting) but does anyone have an idea on how to make a for loop or maybe a while statement where this code can work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
cout << "Welcome to Hangman!" << endl << endl;

string hangmanWords [4] = { "computer", "charcoal", "refrigerator", "automobile" } ;
srand(time(NULL));
int hangmanShuffler = rand() % 4;

string wordToGuess = hangmanWords [hangmanShuffler];

//Set up an array with the letters in the word to guess
int wordToGuessLength = hangmanWords [hangmanShuffler].length();
cout << "Your word has " << wordToGuessLength << " letters in it" << endl << endl;

string lettersToGuess [wordToGuessLength];

int letterInputting;

for ( letterInputting; letterInputting <= wordToGuessLength; letterInputting++ )
{
lettersToGuess [letterInputting] = wordToGuess [letterInputting];
}

cin.clear();
whatNext();
}
Lines 15,17: You never initialize the starting value of your loop.
The termination condition of your loop is incorrect.

Your loop should be:
 
for ( letterInputting=0; letterInputting < wordToGuessLength; letterInputting++ )

Thank you!
I see several possible problems:

1. The following is not allowed in C++ programs:
1
2
3
int wordToGuessLength = hangmanWords [hangmanShuffler].length();
...
string lettersToGuess [wordToGuessLength];

This is a Variable Length Array which the C++ standard doesn't support.

2. The following is accessing that VLA out of bounds.
1
2
3
int letterInputting;

for ( letterInputting; letterInputting <= wordToGuessLength; letterInputting++ )

A. You use letterInputting before it is assigned a value.
B. When you use the operator<= you will access the VLA one past the end. Remember arrays start at zero and end at size - 1.

Topic archived. No new replies allowed.