Question: store .dat file into array.. really confused

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 5909 Views - Last Post: 26 April 2011 - 03:34 PM Rate Topic: -----

#16 TheScandal  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 25-April 11

Re: Question: store .dat file into array.. really confused

Posted 26 April 2011 - 03:22 PM

View Postjimblumberg, on 26 April 2011 - 02:57 PM, said:

Part of your problem is caused by your first for loop.
    indata >> vert;
    
    for(i = 0; i < 9; ++i)  /// Problem is here.
    {
	for(j = 0; j < 3; ++j)
	{
	    indata >> data[i][j];
	    
	}
    }

    cout << vert << endl;
    cout << data[0][0] << endl;
    cout << data[0][1] << endl;
    cout << data[0][2] << endl;
    cout << data[1][0] << endl;




How many lines does your data file contain?
1 2 3
4 5 6
7 8 9

The first loop should execute once for each line, in this case 3 times.

So using this knowledge the loops should be defined like:

    const int NUMLINES = 3;
    const int NUMROWS = 3
    int indata = 0;
    int num = 0;

    indata >> vert;
    
    for(i = 0; i < NUMLINES; ++i)  /// Problem is here.
    {
	for(j = 0; j < NUMROWS; ++j)
	{
	    indata >> data[i][j];
	    
	}
    }


Notice I replaced the constants with a constant.

Now if you have your number of lines and number or rows correct you should be able to read the next piece of data with indata >> num;

Also how have you defined your data variable?

Jim


yea, i caught my problem when I was screwing with it more. but i got it to work!!! So happy!

this is my code

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream indata;
    int data[3][3];
    int data1[2][2];
    int vertex[2];
    int color[2];
    size_t i, j;
    int vert, num;

    indata.open("attempt1.dat");

    if(indata.fail())
    {
	cout << "error" << endl;
	return EXIT_FAILURE;
    }

    indata >> vert;


    for(i = 0; i < 3; ++i)
    {
	for(j = 0; j < 3; ++j)
	{
	    indata >> data[i][j];
	    cout << data[i][j] << endl;
	}
    }

    indata >> num;
    cout << num << endl;

    for(i = 0; i < 2; ++i)
    {
	for(j = 0; j < 2; ++j)
	{
	    indata >> data1[i][j];
	    cout << data1[i][j] << endl;;
	}
    }
    

    indata.close();
}



it prints out

1
2
3
4
5
6
7
ect...
2
10
11
12
13


whoa! I got it. Thanks so much dude. U really helped me a lot!

This post has been edited by TheScandal: 26 April 2011 - 03:25 PM

Was This Post Helpful? 0
  • +
  • -

#17 jimblumberg  Icon User is offline

  • member icon

Reputation: 5304
  • View blog
  • Posts: 16,521
  • Joined: 25-December 09

Re: Question: store .dat file into array.. really confused

Posted 26 April 2011 - 03:34 PM

Glad you got it to work. Remember, when trying to learn new features to start simple. Once you figure out the new features it should be much easier to implement the final solution.

Jim
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2