for

Hello,

I want to ask,
1
2
3
4
5
for(int i = 0;i < many;i++)
{
    getline(cin,other[i].name);
}
cout << other[0].name;

In this program other[0].name is what I input in the for statement, but in
1
2
3
4
5
for(auto i : other)
{
    getline(cin,i.name);
}
cout << other[0].name;

In this program other[0].name is not what I input in the for statement.
Why is it like this??

Nb : other is a struct
Last edited on
In the second case, the variable "i" is basically the same as "other[i]" in the first for-loop. The first time it loops, "i" is the same as "other[0]", the second time "other[1]", and so on.

EDIT: My bad, mis-read the question
Last edited on
Your second example is using a copy of your array, so any changes made to the copy is not made to the original.

You need to use a reference (&) to change the actual value in your array:

1
2
3
4
5
for (auto& i : other)
{
    getline(cin,i.name);
}
cout << other[0].name;
Topic archived. No new replies allowed.