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:
The
<vector>header is included at the top of the file to give us access to thestd::vectortype.A
std::vectorholdingfloatis declared before the for-loop.Inside the for-loop a
floatvalue is put into a variable before being added to the end of the vectorinputsusingpush_back.