从文本文件读入数据到动态二维数组,文件中定义数组大小

本文实例主要是有关OPENGL绘制地形的,文本文件定义了地形数据,格式如下:

colour 0.1 0.2 0.3
size 4 4 1.0
v 1.56 2.34 3.45 4.56 5.89
v 2.12 3.45 4.55 5.67 6.88
v 3.23 4.34 5.67 6.78 7.44
v 4.34 5.66 6.22 7.34 8.12
v 5.12 6.23 7.44 8.12 9.11

colour定义了opengl的rgb颜色

size定义了大小,4*4,间隔1.0 ,所以是5*5的点数,后面的v都是每个点的高度。


<pre name="code" class="cpp">// ReadFileToArray.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <malloc.h>
#include <string>

using namespace std;

int width,depth;
int nrows=0,ncolums=0;
float wstep,dstep,step;
float r,g,b;
float **arr;

/*
定义的地形格式如下
colour 0.1 0.2 0.3
size 4 4 1.0
v 1.56 2.34 3.45 4.56 5.89
v 2.12 3.45 4.55 5.67 6.88
v 3.23 4.34 5.67 6.78 7.44
v 4.34 5.66 6.22 7.34 8.12
v 5.12 6.23 7.44 8.12 9.11
*/

void Init()
{
	int j=0;
	int k=0;
	string str,str1;
	ifstream file;
	file.open("terrain.dat",ios::in);
	if(!file)
	{
		cout<<"Can't open terrain.dat"<<endl;
	}
	else
	{
		while(!file.eof())
		{
			getline(file,str);
//			printf("%s",str.c_str());
			istringstream iss(str);
			iss>>str1;
			if(str1=="colour")
			{
				iss>>r>>g>>b;
			}
			else if(str1=="size")
			{
				iss>>width>>depth>>step;
			}
		}
	}
//	printf("r=%f,g=%f,b=%f\n",r,g,b);
	file.close();
	nrows=width/step+1;
	ncolums=depth/step+1;
	arr=(float**)malloc(sizeof(float)*nrows);
	for(int i=0;i<nrows;i++)
		arr[i]=(float*)malloc(sizeof(float)*ncolums);
	file.open("terrain.dat",ios::in);
	if(!file)
	{
		cout<<"Can't open terrain.dat"<<endl;
	}
	else
	{
		while(!file.eof())
		{
			getline(file,str);
			istringstream iss(str);
			iss>>str1;
			if(str1=="v")
			{
				for(k=0;k<ncolums;k++)
					iss>>arr[j][k];
				j++;
			}
		}
	}
	file.close();
}

void printarr()
{
	printf("r=%f,g=%f,b=%f\n",r,g,b);
	printf("width=%d,depth=%d,step=%f,nrows=%d,ncolums=%d\n",width,depth,step,nrows,ncolums);
	for(int i=0;i<nrows;i++)
	{
		for(int j=0;j<ncolums;j++)
			printf("%f ",arr[i][j]);
		printf("\n");
	}

}

int _tmain(int argc, _TCHAR* argv[])
{
	Init();
	printarr();
	free(arr);
	arr=NULL;
	return 0;
}


 


运行后如图所示:



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值