Reading txtfile into 2d array

This is a discussion on Reading txtfile into 2d array within the C++ Programming forums, part of the General Programming Boards category; Hi all, Im currently working on my first data structure assignment and we are required to read into data from ...

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    22

    Reading txtfile into 2d array

    Hi all, Im currently working on my first data structure assignment and we are required to read into data from a txt file into a 2-d array.

    the txt file has whole numbers that I'll need to use to find craters, but the problem im having is that I can't seem to read it in correctly without the code going bananas and keep printing. Our instructor has given us a constant value for the 2d array and this is what I think is screwing it up, well this is what I have so far
    Note: The constant value for the 2d array is 25

    Code:
    void Terrain::LoadMap(ifstream &in)
    {
      ifstream infile; 
      if(infile.fail())
         {
           cout << "failed" << endl; 
          }
    
    else
    {
    //start processing data
    int grid_map[N][N]//N = 25
    for(int r = 0; r < N; r++)
         {
          for(int c = 0; c < COLUMNS; c++)
         {
          infile >> grid_map[r][c]; 
          }
           }
    //when I begin to print, it keeps giving me magic values and just keeps printing
    for(int r = 0; r < N; r++)
         {
          for(int c = 0; c < N; c++)
          {
           cout << grid_map[r][c] << "\t"; 
           }
           cout << "\n"; 
           }
    So can someone guide me as what I have to do to stop reading into the extra values (beyond the 6x7 grid?) Do I need to keep a companion variable???
    Thanks in advance!!

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,498
    > for(int c = 0; c < COLUMNS; c++)
    Why isn't this N ?

    > to stop reading into the extra values (beyond the 6x7 grid?)
    How does this relate to 25?

    Are you saying there is extra data on the end of each line of the text file that you're supposed to ignore?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    22
    Sorry I have to edit the COLUMNS part out and replace it with N, sorry I was typing that very quickly I lost track.

    What I mean by stop reading into the extra values past the 6x7 grid is this: Our instructor has kept an integer constant of 25 for the 2d array meaning this
    gridmap[25][25]...e.g., int N = 25;
    but the catch here is that in text file he provides us, data is only made up of 6 rows and 7 colums, which means that theres only 42 data values. So if I keep reading into into N, which I did in the loop, theres some magic numbers that keep printing and hence 625 values end up being printed.

    Code:
    for(int r = 0; r < N; r++)
         for(int c = 0; c < N; c++)
               infile >> gridmap[r][c]; 
    //now when I begin to print
    for(int r = 0; r < N; r++)
    {
         for(int c = 0; c < N; c++)
             {
              cout << gridmap[r][c] << "\t"; 
              }
         cout << "\n"; 
    }

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,498
    > Sorry I have to edit the COLUMNS part out and replace it with N, sorry I was typing that very quickly I lost track.
    So lemme get this right.

    What you posted isn't a ctrl-a ctrl-c ctrl-v copy of your code at all, but some half-assed scribble from memory of what you imagine the problem to be.

    Is replying with the next obvious fault going to be a similar waste of my time because you're going to reply "oh, my real code doesn't have that...."?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    407
    I am not sure how exactly you are trying to do this since I can't see the whole code, but I wrote something similiar when I wanted a quick way to make maps for a 2d RPG I made. I built a terrain editor which saved my 2d array into a .txt and then the RPG engine loaded these files in reference to where you were. I will show the commands I used but not how I used them since this is a school assignment.

    Code:
    myfile.is_open()   // to check if the file is open before I read from it
    myfile.eof()   // to set a loop condition to prevent reading after the file is over
    getline(myfile, line) // gets one line of the file myfile and saves it as a string line
    you should be able to put to together based on this alone... make sure to save your string line over to something else before it reads a new line, because getline will change the value of line everytime it processes. I could be wrong but it looked like you were saving the entire file everytime you read it, which would obviously cause you to end up with a ton more variables if you saved every number into each position in the 2d array.... Sorry I can't be more help, but I've written the one savefile and loadfile class and then used it in every other program I had.

    My code did turn out to be occasionally glitchy when I started making increasingly complex maps (2d arrays).

    It would help if you showed what type of variable your 2d array is declared as. Hope this helps.

  6. #6
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,425
    if you KNOW your array has dimensions 6 and 7 then why are you slavishly counting beyond that to n 25? it will not work accessing beyond the bounds of the array will produce nonsense results
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  7. #7
    Registered User
    Join Date
    Apr 2010
    Posts
    22
    This is the header that our instructor gave us for Terrain
    Code:
    #define N 25
    using namespace std; 
    #include <iostream>
    #include <stdlib.h>
    #include <fstream>
    class Terrain
    {
    private:
    	int rowsize;
    	int columnsize;
    	int gridmap[N][N];
    public:
    	////Terrain();
    	//Terrain(int m, int n);
    	void LoadMap(ifstream &in);
    	void PrintMap();
    	//int GetElevation(int i, int j);
    	//int GetRowSize();
    	//int GetColumnSize();
    
    };
    at the very beginning he has given us a max array size of 25 named N
    Note I've also commented out all the other functions that I haven't finished yet

    Now onto the actual definition I have
    Code:
    #include <iostream>
    #include <stdlib.h>
    #include <fstream>
    #include "Terrain.h"
    using namespace std; 
    
    void Terrain::LoadMap(ifstream &in)
    {
    		const int ROWS = 6; 
    		const int COLUMNS = 7;  
    		cout << "Loading terrain information...\n\n"; 
    		for(int i = 0; i < ROWS; i++)
    		{
    			for(int j = 0; j < COLUMNS; j++)
    			{
    				in >> gridmap[i][j]; 
    			}
    		}
    }
    
    
    void Terrain::PrintMap()
    { 	
    	const int ROWS = 6; 
    	const int COLUMNS = 7; 
    	cout << "Printing terrain information...\n\n"; 
    	for(int r = 0; r < ROWS; r++)
    	{
    		for(int c = 0; c < COLUMNS; c++)
    		{
    			cout << gridmap[r][c] << "\t"; 
    		}
    		cout << endl; 
    	}
    }
    Now I've slightly altered the code since Ive held constants for the number of rows and columns, which are respectively 6 and 7. But im still wondering..would it be possible to keep the constant value of N(25) in my nested for loops when I read into my array instead of keeping the constants ROWS and COLUMNS? So is there a way around this?

    Here's the driver
    Code:
    ifstream input; 
    	input.open("C:\\terrain_info.dat", ios::in); 
    	discard_line(input); 
    	if(input.fail())
    	{
    		cout << "cant be opened"; 
    	}
    	else
    	{
    	Terrain map; //created instance of terrain called map
    	map.LoadMap(input); //used that instance to load the map coordinate
    	map.PrintMap();  //used that instance to print contents of the map 
    	}

  8. #8
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    407
    well you should want to print your map based on the 25/25 if that is the size of the terrain. Isn't the text file just so you can read where the crators are, and not the size of your entire terrain?

  9. #9
    Registered User
    Join Date
    Apr 2010
    Posts
    22
    The text file just gives us a bunch of numbers, and our program is to determine which numbers out of these are craters. I honestly don't know why he gave us a 25 constant, he even gave us the 6 x 7 note in the first line of the text file. But I'll try printing the map with the 25 constant limit.

    Edit: I just tried printing the map with the 25 limit, the actual values got printed out along with -8959695. Sticking with the ROWS/COLUMNS limit it printed just fine.
    Last edited by cool_guy; 09-14-2010 at 11:23 PM.

  10. #10
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    407
    well of course it will throw up random numbers..again you haven't defined values to anything but 6x7.

    For you to understand me better. I assumed 2 things.
    1. Your professor KNEW what he was assigning and gave the correct tools to finish the program.
    2. Your text file didn't contain ALL the information for the terrain, but only the location of crators.

    if the map is supposed to be 6x7 like you say and you have that working then move onward to writing your other functions.

  11. #11
    Registered User
    Join Date
    Apr 2010
    Posts
    22
    Yes the text file doesn't contain all the info for the terrain only location of the crators, the elevation of the crators are in a different txt file, but that only has to go inside a 1d array and then I have to write if/else statements to figure out which one is a crater or not. Hey thanks for your input everyone.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reading from a 2d array
    By roaan in forum C Programming
    Replies: 2
    Last Post: 09-04-2009, 06:30 AM
  2. reading bitmap into array
    By kallistine in forum C Programming
    Replies: 35
    Last Post: 07-26-2009, 03:44 PM
  3. 2D array becoming "deallocaded"
    By Aaron M in forum C Programming
    Replies: 2
    Last Post: 09-23-2006, 07:53 AM
  4. Copying from one 2d array to another....with a twist
    By Zildjian in forum C++ Programming
    Replies: 2
    Last Post: 10-24-2004, 07:39 PM
  5. 2d array problem
    By LiLgirL in forum Windows Programming
    Replies: 1
    Last Post: 03-15-2004, 01:23 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21