-1

I'm currently learning programming and learning C++. I'm trying to use the for each loop to print out an array but I'm getting some weird outputs. Here's my code.

#include<iostream>
using namespace std;
int main(){
        int length;
        cin >> length;
        cout << "Enter " << length << " numbers!\n";
        int x[length];  
        for (int i : x){
                cin >> i;
        }
        for (int i : x){
                cout << i << endl;
        }      
        return 0;
}

I ran a test and here's my input and output

5
Enter 5 numbers!
1
2
3
4
5
78344035
1
2031166200
32767
1528080880

If someone could tell me what I did wrong I'd really appreciate it. Thanks

jack klompus
  • 244
  • 1
  • 2
  • 9

1 Answers1

2

Your first loop copies each element of x into i, and you are streaming into that copy i each time:

for (int i : x){
      cin >> i;
}

To stream into the array, take each element by reference:

for (int& i : x){
            cin >> i;
}

See this answer

Again, you are making use of VLA's which isn't standard C++

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68