string of user input to int array[]

hello i'm looking for a way to store user input such as: 1 12 100 2 into an integer array that doesn't necessarily need to have a fixed size. my code so far:

1
2
3
4
5
6
7
#include <iostream>
using namespace std;
int main()
{
cout<<"enter a sequence of numbers separated by spaces"<<endl;
int array[4];
cin>>array[];
Are you familiar with dynamic arrays/dynamic memory? Because the answer to your question revolves around that, which is in turn based on pointers. But even in that case, you have two scenarios:

-The size of your list is predetermined by the user, and not by you, i.e. at runtime, you ask the user to enter the size of his list.

-The size of your list isn't really determined, so you need to start with an arbitrary size, say 10. One you hit 10 elements, you create another array, say of 30 elements, move in the elements from the old array, and keep inputting new elements, and so on.



Alternatively, since you're working with C++, you can use the vector class in STL. It can do all of that work for you. But I think you're not familiar with pointers to start with and you must learn that first.
Last edited on
sorry it's been a while and can't really remember that, i do remember using something similar to store a char array instead of a string.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;
int main()
{
int max = 10;
int* a = new int[max];
cout<<"enter a sequence of numbers separated by spaces"<<endl;
cin>>a[];
return0;
}

i'll worry about resizing the array later but for now it would help me a lot if you can show me how i would store that line of numbers with the space being the del meter. my bad the size of the array will be determined by the user during run time but to keep things simple lets assume the user can only enter 10 for now
Last edited on
Say can store up to 4 integers, you can do this:
cin >> a[0] >> a[1] >> a[2] >> a[3];
You don't need to worry about the space.

Is that what you're looking for?
Topic archived. No new replies allowed.