Custom Input Number

Custom input number.

In task 1.7.8 this code was given to demonstrate when dynamic arrays would be usefull.

#include <iostream>

int main()
{
    std::cout << "How many inputs do you want?";
    int input_count;
    std::cin >> input_count;

    for (int i = 0; i < input_count; i++)
    {
        std::cout << "Input your number";
        std::cin >> ???; // Where can we save all our inputs?
    }
}

Use std::vector and push_back() to fill in this program to collect all of the users inputs.

Answer

#include <iostream>
#include <vector>

int main()
{
    std::cout << "How many inputs do you want?";
    int input_count;
    std::cin >> input_count;

    std::vector<float> inputs;
    for (int i = 0; i < input_count; i++)
    {
        std::cout << "Input your number";
        float input;
        std::cin >> input;
        inputs.push_back(input);
    }
}

3 additions have been made:

  1. The <vector> header is included at the top of the file to give us access to the std::vector type.

  2. A std::vector holding float is declared before the for-loop.

  3. Inside the for-loop a float value is put into a variable before being added to the end of the vector inputs using push_back.

Questions