c++从文本文件中读取3列到2D数组或3个单独的数组中

c++ read 3 columns from a text file into a 2D array or 3 individual arrays

本文关键字:数组 3个 单独 2D 3列 文本 文件 读取 c++      更新时间:2023-10-16

我有一个像这样的文本文件:

173865.385  444879.102  0.299
173864.964  444879.137  0.467
173864.533  444879.177  0.612
173864.113  444879.211  0.798
173863.699  444879.244  1.002
173863.27   444879.282  0.926
173862.85   444879.317  0.974
....
....
....(around 200000 rows)

我试图把每一列到一个数组。现在我有了这些脚本:

int ReadDataFromFile(double * DataList[] ,int DataListCount,string &FileName)
{
    ifstream DataFile;
    int CurrentDataIndex = 0;;
    DataFile.open(FileName.c_str(),ios::in);
    if(DataFile.is_open()==true)
    {
        char buffer[200];
        while(DataFile.getline(buffer,200))
        {
            string strdata;
            stringstream ss(buffer);
            for(int i =0;i<DataListCount;++i)
            {
                getline(ss,strdata,' ');
                DataList[i][CurrentDataIndex] = strtod(strdata.c_str(),NULL);
            }
            ++CurrentDataIndex;
        }
    }
    return CurrentDataIndex;
}

int _tmain(int argc, _TCHAR* argv[])
{
    double a[200000],b[200000],c[200000];
    double* DataList[] = {a,b,c};
    int DataCount = ReadDataFromFile(DataList,3,string("D:\read\k0_test.txt"));
    for(int i=0;i<DataCount;++i)
    {
        cout<<setw(10)<<a[i]<<setw(10)<<b[i]<<setw(10)<<c[i]<<endl;
    }
    system("pause");
    return 0;
}

但是它总是告诉一个错误"overflow"。认识这个问题还有别的方法吗?

 double a[200000],b[200000],c[200000];

用完程序的所有堆栈空间,尝试使用std::vector(首选)或使用动态数组,它会在堆上分配内存。

例如:(仅适用于a)

vector<double> a;
a.reserve(200000);

vector<double> a(200000);

double* a = new double[200000];

不要忘记在使用完内存后释放内存:

delete [] a;

两个解决方案:

double a[200000],b[200000],c[200000];移出_tmain,使它们可以成为全局变量。

声明a,b,c为:

double *a = new double[200000]; 
double *b = new double[200000]; 
double *c = new double[200000];

,不要忘记释放他们的delete[]

希望这对你有帮助