Getting user input in a for loop
How can I retrieve the user input inside this forloop. I'll need each number the user enters.
#include <iostream>
using namespace std;
int main()
{
int N;
int num;
cout << "Please Enter N: ";
cin >> N;
for (int i = 1; i <= N; i++)
{
cout << "Interger #" << i << " ";
cin >> num;
}
return 0;
}
Use an array, or better, a vector.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int N;
cout << "Please Enter N: ";
cin >> N;
vector<int> store(N);
for (int i = 0; i < N; i++)
{
cout << "Integer #" << i+1 << " ";
cin >> store[i];
}
cout << "\n\nHere are the numbers:\n";
for (size_t i=0; i<store.size(); ++i)
{
cout << store[i] << '\t';
}
return 0;
}
|
Note, a vector keeps track of its own size, hence the use of
store.size()
at line 22.
size_t
on the same line is just an unsigned integer type.
Topic archived. No new replies allowed.