Home > Software engineering >  Less elements than array size C
Less elements than array size C

Time:09-08

How do you handle less elements inputed into an array than its size? Program won't progress if there are less elements than array size. Is there a way to accept less elements?

const int SIZE = 10;
int arr[SIZE] = {};

cout << "Size of the array is " << SIZE << "\n";
cout << "Input values (Separate values by space): ";

for(int i = 0; i < SIZE; i  ) {
    
    scanf("%d", &arr[i]);   //Scan values separated by space
}

CodePudding user response:

This won't be an infinite loop (the for is dependent on SIZE; it always runs SIZE times).

That said, you should check the return value from scanf. It returns the number of values successfully parsed; if it's less than or equal to 0, you ran out of parsable ints (additional discrimination on the return value and errno can tell you why it stopped parsing additional ints). If you stop receiving ints, you can set the real usable length of the array in a new variable based on the current value of i, and never try to use the uninitialized values beyond the values you actually received.

I'll also note that you're using C , and as such, you'd probably be better off just reading into a std::vector<int> which will resize as needed removing the need to explicitly size your storage. You could just read in the data with:

const int SIZE = 10;

cout << "Input values (Separate values by space): ";

// If you just want to slurp all values
std::vector<int> arr(std::istream_iterator<int>(cin), std::istream_iterator<int>());

// If you want to slurp a fixed number of values
std::vector<int> arr;
for(int i = 0; i < SIZE; i  ) {
    int tmp;
    if (!(cin >> tmp)) {
        break;
    }
    arr.push_back(tmp);
}
// arr.size() will tell you how many items you actually read

CodePudding user response:

Is there a way to accept less elements?

Yes. If there is no input std::scanf will return EOF. Hence, you could write the loop condition like this:

for(int i = 0;
    i < SIZE && std::scanf("%d", &arr[i]) != EOF;
    i  )

Sidenote: An array always has constant number of elements. In this case, there are 10 elements regardless of how many of them you assign in the loop. You could use a data structure such as std::vector to have exactly as many elements as are inputted.

SIdente 2: I recommend against using std::scanf. It's much easier to not make mistakes with the iostream API.

Sidenote 3: Consider whether (and if yes, then how) you need to handle invalid input.

CodePudding user response:

In this case use an object of the type std::string and the function std::getline to read the whole string of numbers. Then extract numbers from the string for example by using std::istringstream or std::stoi.

Something like

    const size_t SIZE = 10;
    int arr[SIZE] = {};

    std::string input;
    size_t n = 0;

    do
    {
        std::cout << "Size of the array is " << SIZE << "\n";
        std::cout << "Input values (Separate values by space): ";

        std::getline( std::cin, input );

        std::istringstream iss( input );
        n = std::distance( std::istream_iterator<int>( iss ),
                           std::istream_iterator<int>() );

        if ( SIZE < n )
        {
            std::cout << "Too many values. Repeat input.\n";
        }                            
    } while ( n <= SIZE );                            

    std::istringstream iss( input );

    std::copy( std::istream_iterator<int>( iss ),
               std::istream_iterator<int>(),
               std::begin( arr ) );
  • Related