program stuck when reading file on.get function
Question
I'm creating a program on win32, the program stops responding on .get function, I don't know what to do else, I think the problem is with std::ifstream inFile;
but I need it outside of the main program, so I can use it in everywhere, for example here I use inFile in WM_CREATE and also in WM_KEYDOWN and close the file when the window closes. is it posible to do?
char Map[10][10], c[256];
std::ifstream inFile;
//windProc
case WM_CREATE: {
inFile.open ("Map.txt");
if (!inFile) {
::MessageBox(hwnd, "Failed to open file", "Error", MB_OK);
}
int i,j;
do { //loop for skipping comments
Map[j][i] = inFile.get(); //<---stuck here
if (Map[j][i] ==';') inFile.getline(c, 256);
} while (Map[j][i] ==';');
while (Map[j][i] !=';') { //loop for painting
switch (Map[j][i]) {
//
//paint based on char
//
}
i++;
Map[j][i] = inFile.get();
if (i==10) {j++; i=0;}
}
}
case WM_KEYDOWN: {
//...
inFile.getline(c, 256); // continue reading from file
int j=0; int i=0;
Map[j][i] = inFile.get();
while (Map[j][i] !=';') {
switch (Map[j][i]) {
//
//paint based on char
//
}
i++;
Map[j][i] = inFile.get();
if (i==10) {j++; i=0;}
}
break; }
case WM_DESTROY:
inFile.close();
PostQuitMessage (0);
break;
Solution
Your problem is that you're not initializing i
and j
. Try initializing them to 0
. Also, you presumably want to update them in your loop so you don't continuously store the character in the same element.
Then you need to reinitialize i
and j
to 0
before the painting loop. However, painting is usually done in WM_PAINT
(I'm not even sure it'll work in WM_CREATE
.)
OTHER TIPS
If the steam enters error/eof state in your while loop, Map[j][i]
won't ever be set to ';'
resulting in an endless loop:
do { //loop for skipping comments
Map[j][i] = inFile.get(); //<---stuck here
if (Map[j][i] ==';') inFile.getline(c, 256);
} while (inFile.good() && Map[j][i] ==';');