Problem with reading value in dynamic allocated array

Hi all,
I have written a source code that is as below;

# include <iostream>
# include "conio.h"
# include <stdio.h>
using namespace std;

int main ()
{
size_t result;
long num_value;
int result_of_feof;
int i;

/* open file by fopen */
FILE *pFile;
pFile = fopen ( "experiment.txt" , "r" );//content inside this file is:1.00 2.00 3.00 4.00 5.00
if (pFile==NULL) {cout<<"fopen fail"<<"\n";}
else {cout<<"fopen successful"<< "\n";}


/* obtain number of value in the file which is five of them in this case */
fseek (pFile , 0 , SEEK_END);
num_value = ftell (pFile);
rewind (pFile);
cout<< "number of value in file is"<<" "<<num_value<<"\n";

/* allocate dynamic memory array */
float *pArray;
pArray = new float [num_value];
if (pArray==NULL) {cout<<"memory allocation fail"<<"\n";}
else { cout<<"memory allocation successful"<<"\n";}

/* read the values in the file into the allocated memory space */
result = fread (pArray, 1, num_value, pFile);
if (result != num_value) {cout<<"fread fail, value not copy into array"<<"\n";}
else {cout<<"fread successful, value copied into array"<<"\n";}


/* display value "3" in pArray to console */
cout<<pArray[3];//this line got problem
delete [] pArray;

_getch();
return 0;
}

My problem is when i debug, the value display on the console was not "3". Instead some funny number "6.31245e-001".

Can anyone give me a clue on how to get the value store in the array display on the console when debug?

Thanks alot!
First comment is that you want pArray[2] not [3]. Arrays are accessed with zero based offsets. That being said, I think that you are approaching this in the wrong way. I don't think that you are sizing the array correctly. Did you use the debugger yet? I recommend that you step through the code with the debugger. I'll bet that you will be surprised when you start looking at the values of the variables as they are filled. This is the kind of problem that debuggers were made for.
I would also suggest that you use the program output tag button to the right of the edit box. Copy and paste all text from the console. Highlight it and press the tag button to the right. It's the middle one on the top row. You are printing num_value. Is 5 being printed? I seriously doubt it. The array needs a size of 5 since there are 5 values in the text file. However, you are sizing it using the number of bytes in the file. Then you are using a binary read to copy ascii characters into a float array.

I recommend that you read the entire section of FAQs below on the IO stream libs, for starters.
http://www.parashift.com/c++-faq-lite/input-output.html

Then read about the vector and other container classes here.
http://cplusplus.com/reference/stl/
Thanks for the suggestion!
Will look into it.
Topic archived. No new replies allowed.