Just got back to my interrupted attempt to pick up C++, and I'm already shipwrecked again. Anyway...

I'm trying to build another bitty app from my text, but nothing seems to be coming together properly. The program should ask for an array length, send that to an input-handling function, then send all of that on to a display function. Then, the last part reverses the contents of the array. As it is, however, I think my input function is shooting garbage into the slots following my array, and my display function is utterly failing\b\b\b\b\b\b\bfine. I THINK the last part actually works.

/** Chapter 7, Exercise 6
    array flip & fill thingie
*/
#include <iostream>

int fill_array(double ar[], int arSize);
int show_array(const double ar[], int arSize);
void reverse_array(double ar[], int arSize);
using namespace std;

int main()
{
    int array_size;
    cout << "Chapter 7, Exercise 7: Fill & flip\n\n";
    cout << "Enter the size of the array: ";
    cin >> array_size;
    cin.clear();
    double list[array_size];
    array_size = fill_array(list, array_size);
    show_array(list, array_size);
    reverse_array(list, array_size);
    show_array(list, array_size);
    return 0;
}

int fill_array(double ar[], int arSize)
{
    cout << "Input value #1: ";
    int i = 0;
    while ((cin >> ar[i]) && (i < arSize))
    {
        i++;
        cout << "Input value #" << i + 1 << ": ";
    }
    return i;       //should return the actual number of values entered
}

int show_array(const double ar[], int arSize)
{
    cout << "Array contents: \n";
    if (arSize == 0)
    {
        cout << "No data";
        return 1;           // can use this to cut off future processing
    }
    for (int j = 0; j < arSize; j++)
    {
        if ((j > 0) && (j % 10 == 0))
            cout << endl;   // line break every 10 items?
        cout << ar[j] << " ";
    }
    cout << endl;
    return 0;
}

void reverse_array(double ar[], int arSize)
{
    double * rev = new double[arSize];
    int i, j;
    for(i = 0, j = arSize; i < arSize; i++, j--)
        rev[j-1] = ar[i];
    for(i = 0; i < arSize; i++)
        ar[i] = rev[i];
}

Any kindly souls have a clue what's wrong?

Edit: My vision's not so hot. I had an "=" instead of an "==" in the little empty-array check in my display function. The input section's still not working properly, though...

Edited 6 Years Ago by grib: n/a

From :

while ((cin >> ar[i]) && (i < arSize))

To :

while ((i < arSize) && (cin >> ar[i]) )

Edited 6 Years Ago by firstPerson: n/a

Wow. Never thought about what order those things would be processed in -- that'll teach me. Thanks for the snappy assistance!:icon_smile:

This question has already been answered. Start a new discussion instead.