'Insert values from long variable into array and read values

I'm working on a program that takes a long variable (x) and stores it into an array, then is able to read the separate values both reversed and in order. I've used a while loop in order to store the values but am a little stuck getting the program to read the values, but practices like this will help my understanding of the subject in the long run. Any advise on where I'm making a mistake would be great, thanks in advance! I'm still kind of a n00b with arrays in C++

    int arr[]={};
    long x;
    int i=0;
    int j;
   
    
    
    cout<<"Enter value to be stored: "<<endl;
    cin>>x;
    
    
  while(x>0){
       int lastdigit=x%10;
        arr[i]=lastdigit;
        x=x/10;
       
    } 
    if(arr[i]>0){
    for(j=i-1;j>-1;j--){
        cout<<"Array values "<<arr[j];
    }

}
}

This is just to read the array values in order, I'll add the reversal once I get this part down.



Solution 1:[1]

Your fundamental error is here

int arr[] = {};

this creates a zero size array if it was allowed but on my machine its not even valid syntax

cannot allocate an array of constant size 0 ConsoleApplication1 C:\work\ConsoleApplication1\ConsoleApplication1.cpp 12

I changed it to

 int arr[12] = {};

since 10 decimal digits is enough for a 32 bit integer, plus one to be sure, and another one just in case :-)

Next mistake is you never increment i in the mod / divide loop

Then finally you test arr[i] > 0. This is not needed, take it out

Now your code works fine

PS. Make arr a std::vector<int> so it will grow rather than hard coding to 12 digits

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1