#include <iostream>
#include <iomanip>
#include <math.h>
#include <string>
#include <fstream>
 
using namespace std;
 
const int SIZE = 10;
 
// note that arrays always act like the reference (&) we saw last week
void newandimproved(int in[SIZE][SIZE],int out[SIZE][SIZE]) {
	for(int row = 0; row < SIZE; row++) {
		for(int col = 1; col < SIZE-1; col++) {
			// the following only works if col is in the range 1 through SIZE-2.
			// Note the loop is changed to do this.
			out[row][col] = int(((in[row][col+1])*321)%(in[row][col-1]+7));
		}
	}
	// What about the first and last columns? Lets fill those too.
	for (int row = 0; row < SIZE; row++) {
		out[row][0] = 1;
		out[row][SIZE-1] = in[row][2];
	}
 
}
int main()
{
	int land[SIZE][SIZE]; // The array that holds elevations for your landscape.
	int newland[SIZE][SIZE];
 
	// First set up the landscape as a smooth hill
	for(int rows = 0; rows < SIZE; rows++) {
		for(int cols = 0; cols < SIZE; cols++) {
			land[rows][cols] = cols;
		}
	}
 
	// Put in a few bumps
	land[3][4] = 2*land[2][3];
	land[0][0] = 10;
 
	// Now print it out
	cout << "Here is land:" << endl;
	for(int row = 0; row < SIZE; row++) {
		for(int col = 0; col < SIZE; col++) {
			cout << land[row][col]<<",";
		}
		cout <<endl;
	}
 
	//use new and improved
	newandimproved(land,newland);
	cout << endl << "And here is newland:" << endl;
	for(int row = 0; row < SIZE; row++) {
		for(int col = 0; col < SIZE; col++) {
			cout << newland[row][col]<<",";
		}
		cout <<endl;
	}
 
	// Now write it to a file
	cout << "Where would you like to write the file?"<<endl;
	string filelocation;
	getline(cin,filelocation); // Important to use getline here, there may be blanks in the file name
        // Also remove "s, windows adds them in some cases
	if (filelocation.substr(0,1) == "\"") {
		filelocation = filelocation.substr(1,filelocation.length()-2);
	}
 
	cout << "FYI, writing to " << filelocation << endl;
	ofstream myfile (filelocation); // Open the file at the location the user asks for
	if (myfile.is_open()) // If it worked write out the values
	{
		for(int row = 0; row < SIZE; row++) {
			for(int col = 0; col < SIZE; col++) {
				myfile << newland[row][col]<<","; // This is just like cout, except it writes to the file
			}
			myfile <<endl;
		}
 
		myfile.close();
	}
	else {
		// If the file open didnt work, print out an error
		cout << "Unable to open file";
	}
	system("pause");
}
cs-142/2d-arrays-and-files.txt · Last modified: 2015/10/14 11:51 by kseppi
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0