Hello, so I was trying to make a c++ console game "Gallows" for school, and I've noticed, that my program (Its not the full game, its only beginning, but I can't do anything with this error.) doesn't run - Windows is showing "Program has stopped working message". Please help :/. !!! The problem somehow starts when while loop begins.
# include <iostream>
# include <ctime>
# include <cstdlib>
# include <fstream>
# include <string>
usingnamespace std;
int main(){
srand(time(0));
ifstream myFile("zodziai.txt");
int x;
myFile >> x;
int y = x;
string word[x];
while(myFile>> word[x]){
x--;
}
y = 1+rand()%y;
string zodis = word[y];
int ilg = zodis.length();
//^Word (Gets word from txt file. Text in that file is like this: 2(nr of words) word1 word2)
string mask = zodis;
int i = 1;
while(ilg >= i){
mask.replace(i-1,i,"*");
i++;
}
//^Mask
char guess[7];
int lives = 7;
int a=0;
while(lives != 0&&mask!=zodis){
cout << "Zodis: " << mask << endl;
cout << "Spejimas: " ;
cin >> guess[a];
lives --;
a++;
}
return 0;
}
Is illegal C++. You should know array size in compile time.
2)
1 2 3
while(myFile>> word[x]){
x--;
}
Firstly your first read is writing out of bounds: there is no word[x] element. Possible crash.
Second, there is no limit on amount of words read. If file does not contain exactly x words, your code will read data in elements -1, -2, etc. leading to crash
3) y = 1+rand()%y; can generate out of bound value again.
Hello, Thank you for quick reply, but it isn't the problem. I probably should have mentioned, that the code worked fine until while(lives != 0&&mask!=zodis) loop.
Those are problems. You just didn't run in them yet.
First one in particular prevents majority of people from even compiling your code, as non-standard extension usually is not used.
Last loop works fine and should not crash. How did you knew that problem is here?
What is your input?
Did you fix all problems? mainly 2 and 3. Your fixed code works perfectly for me.
Post content of your file.
Try to get stack trace of the moment of your crash.
What IDE are you using?
Edit: your string replacement looks sketchy. second paremeter is how many characters to replace. Each iteration you are replacing more and more characters until i becomes larger than string size. This leads to exception.
Replace lines 33-37 with std::string mask(zodis.size(), '*');And fix other out of range errors.