Search code examples
c++fstreamfile-io

C - Strange values while reading text file with fstream


I wrote a function to read a text file, create an array from the integer values in the file and return the reference of that array to main function. The code I wrote(in VS2010):

//main.cpp
void main(){
int T_FileX1[1000]; 
    int *ptr=readFile("x1.txt");

    for(int counter=0; counter<1000; counter++)
        cout<<*(ptr+counter)<<endl;    
}

and the function is:

//mylib.h 
int* readFile(string fileName){
    int index=0;
            ifstream indata;
            int num;

    int T[1000];    
    indata.open("fileName");
            if(!indata){
                cerr<<"Error: file could not be opened"<<endl;
                exit(1);
            }
            indata>>num;
            while ( !indata.eof() ) { // keep reading until end-of-file
                T[index]=num;       
                indata >> num; // sets EOF flag if no value found
                index++;
            }
            indata.close();

            int *pointer;
            pointer=&T[0];
            return pointer;
}

the data in the file contains positive numbers like

5160
11295
472
5385
7140

When I write each value in "readFile(string)" function, it writes true. But when I wrote it to screen as U wrote in "main" function, it gives values strangely:

0
2180860
1417566215
2180868
-125634075
2180952
1417567254
1418194248
32   
2180736

irrelevant to my data. I have 1000 numbers in my file and I guess it raves these irrelevant values after a part of true writing. E.g. it writes first 500 values true, and then it writes irrelevant values to my data. Where is my fault?


Solution

  • int T[1000]; 
    ...
    pointer=&T[0];
    

    you are returning a pointer to a local stack variable which is going to get destructed.

    I think what you want to do is to pass in the array T_FileX1 that you have defined to the function and use that directly to read the data into.