I'm having trouble solving this porblem.

Write only the “snippet” of C++ code for a function definition, fillArray, which fills int_array. Repeatedly prompt the user to enter an integer at the keyboard. (Input values should be stored in row order). fillArray has one argument, the 2D array. 'Protect' arrray values from being changed by the function when necessary. This is what I have so far.

void fillArray(int int_array)
{
    for (int row=0; row<rows; row++)
    {
        for (int column=0; column<columns; column++)
        {
            cout <<"Enter an integer:";
            cin>>int_array;
        }
    }
}   

Dani AI

Generated

The current signature in the thread declares a single int instead of a 2D array, and the loops refer to rows/columns that must be known at compile time or passed in. correctly flagged the declaration mismatch, and gave a robust two-argument approach. If the assignment truly requires a single argument, the safest, modern way is to accept the whole array by reference so the compiler knows both dimensions (or use a template that deduces them).

template <size_t R, size_t C>
void fillArray(int (&arr)[R][C]) {
    for (size_t r = 0; r < R; ++r) {
        for (size_t c = 0; c < C; ++c) {
            std::cout << "Enter integer for [" << r << "][" << c << "]: ";
            while (!(std::cin >> arr[r][c])) {
                std::cin.clear();
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                std::cout << "Invalid input, try again: ";
            }
        }
    }
}

This keeps fillArray to a single parameter (the array) while letting the template deduce row/column counts. Invocation is straightforward: e.g. int data[2][4]; fillArray(data);. If dimensions are not compile-time constants, use a dynamic container (std::vector<std::vector<int>>) or the two-argument pattern that showed (array plus row/column counts).

A brief note on “protecting” values: functions that only read should take const references; a filler must be non-const so it can write elements. Prefer size_t for indices and use std::numeric_limits with ignore to discard bad input safely. This approach is type-safe, avoids pointer decay surprises, and directly addresses the declaration and indexing problems raised in the thread.

Recommended Answers

All 2 Replies

fillArray has one argument, the 2D array

void fillArray(int int_array)

Is that how you declare a 2-dimensional array? You declared it differently in your other thread. That one has two brackets in the declaraction. Why doesn't this one? Or why doesn't the other one have no brackets like this one? Clearly both declarations should have 2 brackets or neither should, right?

It is good for you to learn, as early as possible, some simple 'student type' ways to get numeric imput ...

from a keyboard user,

so that the running program will nor crash if invalid data was entered.

The following little demo may help to get you started in that direction.

// fill2Darray.cpp //


/*
    function definition, fillArray,  fills int_array.

    Repeatedly prompt the user to enter an integer at the keyboard.

    (Input values should be stored in row order).

   *here* the fillArray has TWO arguments: 2Dary & num_rows

    'Protect' arrray values from being changed by the function when necessary.
*/

#include <iostream>


// set what you need here ...
const int NUM_COLS = 4;


// An example od a 'student way' to get valid user input
// from keyboard so program will NOT crash
// IF user enters invalid data. //
void fill2Dary( int matrix[][NUM_COLS], const size_t num_rows )
{
    for( size_t r = 0; r < num_rows; ++ r )
    {
        std::cout << "Enter " << NUM_COLS << " integers on the next line, to fill row "
                  << (r+1) << ", then press the 'Enter' key:\n";
        for( size_t c = 0 ; c < NUM_COLS ;  )
        {
            if( std::cin >> matrix[r][c] ) ++c;
            else
            {
                std::cin.clear();
                std::cin.sync();
                std::cout << "Imvalid entry. Please enter whole row "
                          << (r+1) << " again ...\n";
                c = 0;
            }
        }
        std::cin.sync(); // 'flush' any wxtra entries entered at end of row ... //
    }
}


template < typename T >
void output( const T mat[][NUM_COLS], const size_t num_rows, std::ostream& os = std::cout )
{
    for( size_t r = 0; r < num_rows; ++ r )
    {
        for( size_t c = 0; c < NUM_COLS; ++ c ) os << mat[r][c] << ' ';
        std::cout << '\n';
    }
}




int main()
{
    using std::cout;

    const int num_rows = 2;
    int mat[num_rows][NUM_COLS];

    fill2Dary( mat, num_rows );

    cout << "The 2Dary was: \n";
    output( mat, num_rows );
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.