Reputation: 40
OK, so all I am trying to do is simply read some co-ordinates from a text file and use them to draw an array of bricks. I have this code:
ifstream infileScenario("scenario1.txt");
for (int i = 0; i < NUM_OF_BRICKS; i++)
{
// read brick coordinates
infileScenario >> bricks[i].m_x;
infileScenario >> bricks[i].m_y;
cout << bricks[i].m_x << " " << bricks[i].m_y << endl;
// set brick properties
bricks[i].m_height = 0.1;
bricks[i].m_width = 0.2;
bricks[i].life = 3;
}
infileScenario.close();
But the only thing that I am getting printed to the console is a bunch of 0's. I've checked over my code again and again as well as double checking my text file and I still can't see where I am going wrong.
My text file is called scenario1.txt and it's contents are:
-0.6 0.7
-0.3 0.7
0 0.7
0.3 0.7
0.3 0.7
-0.6 0.5
-0.3 0.5
0 0.5
0.3 0.5
0.3 0.5
I wrote these values in myself which, if I had to hazard a guess, would think what could be causing my problem. Could it be to do with text encoding or am I wrong in thinking this?
Upvotes: 0
Views: 343
Reputation: 1467
I would suggest not using the stream classes, they are a little more difficult to check for errors, here is the same code converted (with error checks) using fscanf.
FILE *infileScenario;
int i;
if ((infileScenario = fopen("scenario1.txt", "r")) == NULL) //didnt open readonly
{
printf("Error, could not open scenario1.txt\n");
exit(-1); //terminate program with a code we can read by running echo $?
}
for (i = 0; i < NUM_OF_BRICKS &&
fscanf(infileScenario, "%lf %lf",
&bricks[i].m_x, &bricks[i].m_y) != EOF;
i++)
{
// read brick coordinates
printf("%lf %lf\n", bricks[i].m_x, bricks[i].m_y);
// set brick properties
bricks[i].m_height = 0.1;
bricks[i].m_width = 0.2;
bricks[i].life = 3;
}
fclose(infileScenario);
You can also g++ -g -o and then gdb and run the following in gdb:
b main
r
s
(each time the for loop hits bricks[u].life = 3, run)
p bricks[i]
(otherwise, keep running)
s
That should allow you to diagnose what the issue seems to be, if my solution did not just fix it.
Upvotes: 1