populating a struct from a loop

i know how to make the loop, what I don't know is how to make it add a unique value to the structure on each pass. Forgive me if the code isn't exactly right, i'm typing this off the cuff so there might be some small syntax problems.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct example
{
    std::string var1
    int var2
};

cout << "do you want one?/n"
cin >> want

std::string color
int amt

for (want, want=yes, want)
{
    cout << "what color do you want?/n"
    cin >> color
    cout << "how many do you want?/n"
    cin >> amt
    cout << "do you want any more?/n"
    cin >> want
}


this is why i get hung up. I then want the loop to output something like this
assuming the user said they wanted red, and then wanted 3

example red = {"red", 3};

so the variable red.var1 = "red" and red.var2 = 3

then on the next pass they want orange, and 4

so it would create orange.var1 = "orange" and orange.var2 = 4

they don't have to be named red.var1 and orange.var1, so long as the first portion is unique on each pass of the loop could come out as choice1.var1, choice2.var1, etc.
some small syntax problems.
for (want, want=yes, want)

There are several problems with the code (including no semi-colons) :P

It would look best like:
1
2
3
4
5
6
7
8
9
while( want )
{
    cout << "what color do you want?/n";
    cin >> color;
    cout << "how many do you want?/n";
    cin >> amt;
    cout << "do you want any more?/n";
    cin >> want;
}


Also if you want the type of color to be unique you would have to create a list of them and compare. To the old ones and if it isn't there already then create a new object.


Though if you are just mapping a quantity to a color you should just use a std::map<T,U>.

1
2
3
4
5
6
7
8
std::map<std::string,int> Colors;


Color["Red"] = 3; //new key ("Red") , new value (3)

//now they can't add a new red but they may modify the value

Color["Red"] = 5; //same key("Red") different value(5) 


*missing a forward slash in code tag
Last edited on
i don't see how that ads them to the structure though.

my first thought was that after the questions in the loop i could have something like this

1
2
3

example color = {color, amt};


and the compiler would replace "color" with the value for color from that iteration of the loop. but it doesn't look its doing that. i think this code would just end up with one color.var1, one color.var2, that would overwrite itself each time.
Use a vector of example structures. For each iteration of the loop, push a new instance of the structure onto the vector, containing the new colour and amount.
sorry, i am that much of a beginner. can you give me an example of what that would look like?
Topic archived. No new replies allowed.