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";
/* 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?
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.