c++从文本文件中读取3列到2D数组或3个单独的数组中
c++ read 3 columns from a text file into a 2D array or 3 individual arrays
我有一个像这样的文本文件:
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[]
希望这对你有帮助
相关文章:
- 如何在C++中比较两个char数组
- 在c++中获取两个大int,并将它们存储在数组中
- 如何以优化的方式同时迭代两个间距不相等的数组
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 如何从txt文件中读取多个不同长度的数组?
- C++,数组有多少个地址?
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 为什么 2 个相同数组的元素彼此相等
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 可以将两个相同类型的连续数组视为一个数组吗?
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 使用嵌套函数数组是个好主意吗?
- 链表数组(5 个队列)
- 是否有可能通过溢出 C 中的第一个元素来写入数组第二个元素
- 指向数组第一个元素的指针的地址
- 用 std::valarray 替换 POD C 样式数组是个坏主意吗?
- OpenGL:两个顶点数组 + 两个索引数组
- c++多维数组多个数据类型
- 使用C++AMP处理大型数组(65536+个元素)
- 在c++中使用MKL函数初始化数组是个好主意吗?