I am writing a code that takes a number as the array length and asks the user to input values into it. The problem with my code is that when I print out the values of the array it would give out random values that were never part of the array in the first place. I looked online for all of this and the code just seems right to me but for some reason it is not printing out properly.
#include <iostream>
using namespace std;
int main(){
int x, input;
cout<<"Enter the number of values: "<< endl;
cin >> x;
int arr[x];
cout<<"Enter the values: "<< endl;
for(int i = 0; i < x; i++){
cin>>input;
input = arr[i];
}
cout<<" "<< endl;
for(int i = 0; i < x; i++){
cout<< arr[i]<<endl;
}
return 0;
}
The problem is with this line of yours-
input = arr[i];
Here you are assigning the value of arr[i] to the input variable , in this way you never actually set the value of arr[i] and which is why it stores a grabage value. You should change it to-
arr[i] = input;
Or may be you don't need to use input variable, you can do something like-
cin >> arr[i]; // it will just take the value and assign it to arr[i]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.