Beginner Array question?

sfsf
Last edited on
No no, a 7-dimensional array is never the answer.

The way I would do this is to have an "Art" class (or struct, basically the same thing in C++..., struct is public).
An art class has an artist, title, medium, and all the other things you listed as its properties.

if you know the file has 120 lines and exactly what's in each line, you can do something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
std::vector<Art> art_data; //or plain array with [120] length if you desire

//open file

std::string artist;
std::string title;
std::string medium;
int height;
int width;
//...etc

//Parse file:
for (int i = 0; i < 120; i++)
{
    f >> artist;
    f >> title;
    f >> medium;
    f >> height;
    f >> width;
    Size size(height, width);
    //etc.
    Art art(artist, title, medium... etc); //put the data into an art instance.
    art_data.push_back(art); //add it to array
        //(use just assignment if working with plain array)
}

Last edited on
sdasd
Last edited on
I will never understand why schools teach file streams before things like vectors or at the same time as classes or other data structures /rant

Okay, so in your prompt you said that Each line in your art.dat has a struct called Size.
Doing Size size(height, width); would construct a variable named "size" of type Size with the given height and width.

When I first read the prompt I assumed that those things had already been made for you.
You have to define your own struct called Size, and give it a height and width property.
http://www.cplusplus.com/doc/tutorial/structures/
Note that a struct doesn't need to have a constructor, you can just do something like
1
2
3
4
5
6
7
8
9
10
struct Size {
  int width;
  int height;
} ;

///in your main program:

Size size;
f >> size.height;
f >> size.width;

I'm not sure what you already know so sorry if my posts seem disorganized.

About the art_data variable: It's an std::vector. Here's how you would make it if it's just an array
1
2
3
4
5
Art art_array[120];
...
//for loop
   Art art(artist, title, medium, size, etc.);
   art_array[i] = art;


If you're just using structs and don't want to use a constructor, do something like
1
2
3
4
5
6
Art art_instance;
f >> art_instance.artist;
f >> art_instance.title;
f >> art_instance.medium;
...
art_array[i] = art_instance;


Ignore the vector code you don't need to use vectors, arrays are fine, don't want confuse you anymore than I have...
Last edited on
Topic archived. No new replies allowed.