Boomer Boomer - 3 months ago 26
C++ Question

Ending array input (C++ industry-standards)

The code I've written is working, but I feel like there's probably a better, and standard way to end the input of an array that I may not know about. The code in question is in the getInputForArray() and implemented by stopping the loop if cin.fail() is detected on integer input. Is there a better way? Thanks, all.

#include <iostream>
using namespace std;

int sumOfArray(int arr[], int arrlen);
void getInputForArray(int arr[], int arrlen);

int main() {
const int LIST_SZ = 256;
int mylist[LIST_SZ];
// Zero out the array
for (int i = 0; i < LIST_SZ; i++)
mylist[i] = 0;
// Get user input for array
getInputForArray(mylist, LIST_SZ);
// Print the sum of all the numbers in the array
cout << "\nThe sum is: " << sumOfArray(mylist, LIST_SZ) << endl;
return 0;
}

int sumOfArray(int arr[], int arrlen) {
int total = 0;
for (int i = 0; i < arrlen; i++)
total = arr[i] + total;
return total;
}

void getInputForArray(int arr[], int arrlen) {
cout << "Input any non-numerical value to denote the end of your input\n";
for (int i = 0; i < arrlen; i++) {
if (!cin.fail()) {
cout << "Please input a value for the [" << i
<< "] position of the array: ";
cin >> arr[i];
}
}
}

Answer

Other answers addressed the EOF (or end of input) option.

OP can modify the user input checks to stop the loop when non numerical inputs are entered twice. I also consider a better practice to use a std::vector instead of a raw array.

This is a possible implementation:

std::vector<int> getDataFromInput( size_t max_data )
{
    using std::cout;

    std::vector<int> v;
    std::string value;

    bool stop_reading = false;

    while ( v.size() < max_data )
    {
        cout << "Please input a value for position [" << v.size() << "] of the vector: ";
        // input a string, if End of Input, stop reading
        if ( !(std::cin >> value) ) break;
        try
        {   // if the user entered a valid number, add it to the vector
            int num = stoi(value);
            v.push_back(num);
            stop_reading = false;
        }
        catch ( const std::invalid_argument &e )
        {
            if ( stop_reading ) break;
            cout << "You entered a non-numerical value.\nPlease, enter another "
                 << "non-numerical value to stop input or a number to continue\n";
            stop_reading = true;
        }
        catch ( const std::out_of_range &e )
        {
            cout << "The value entered can't be represented by an int.\n";
        }
    }

    return v;
}