c++ - C - 使用 fstream 读取文本文件时出现奇怪的值

标签 c++ fstream file-io

我编写了一个函数来读取文本文件,根据文件中的整数值创建一个数组,并将该数组的引用返回给主函数。我写的代码(在 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;    
}

函数是:

//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;
}

文件中的数据包含像这样的正数

5160
11295
472
5385
7140

当我在“readFile(string)”函数中写入每个值时,它会写入 true。但是当我像你在“main”函数中写的那样将它写到屏幕上时,它给出了奇怪的值:

0
2180860
1417566215
2180868
-125634075
2180952
1417567254
1418194248
32   
2180736

与我的数据无关。我的文件中有 1000 个数字,我猜它在真实写作的一部分之后对这些不相关的值赞不绝口。例如。它首先写入 500 个值 true,然后将不相关的值写入我的数据。我的错在哪里?

最佳答案

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

您正在返回一个指向将被销毁的本地堆栈变量的指针。

我认为你想要做的是将你定义的数组 T_FileX1 传递给函数并直接使用它来读取数据。

关于c++ - C - 使用 fstream 读取文本文件时出现奇怪的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13796263/

相关文章:

c++ - 嵌套结构和指针

c++ - 将数据加载到结构 vector 中

c++ - std::fstream 的惊人结果

c++ - 尝试将 vector <int>保存在bin文件中并读取它给出了随机数据

c++ - 从具有两列的文件加载二维数组

c++ - 指向数组的指针,为什么这是最后一个元素的地址?

使用 WM_SETCURSOR C++ 光标更改为沙漏

c++ - 文件输出到记事本.txt

c++ - 读写文件

c - 使用指向 FILE 类型的 const 指针是个好主意吗?