Reading List of Numbers into an Array using cin?

For some reason I am having some trouble reading a list of numbers using cin into an array, using -1 to indicate I am done.

For example, the program will prompt for numbers and I will enter: 1 2 3 4 5 -1 and I would want those 5 numbers (1 2 3 4 5) to be stored into an array. I am having trouble doing that!

I was able to get it done using an input stream, but I can't get it right with cin. Here is my input stream code:

1
2
3
4
5
6
7
8
9
10
11
nums[50];
ifstream input;
int count = -1;

input.open("nums.txt");
  
do
{
    count++;
    input >> nums[count];
}while(nums[count] != -1); 


This stores it perfectly fine using an input stream, how I would I use in cin instead? Any help would be greatly appreciated!!!
Last edited on
What problems do you have while using std::cin, and how does your code look like when you use it?

-Albatross
I get stuck in an infinite loop using std::cin. I just tried using a simple code:

1
2
for(int i = 0; nums[i] != -1; i++)
        cin >> nums[i];


... thinking it would read each number into the spot in the array until it hits a -1. It doesn't, it just gets stuck.
Last edited on
1
2
3
4
5
initialization;
while( condition ){
  statements;
  increment; //<---
}
So you write in nums[K] but check nums[K+1]
1
2
3
4
5
6
int k = 0;
while(nums[k+1] != -1)
{
    cin >> nums[k];
    k++;
}


It still doesn't terminate the loop. Note, I am trying to just prompt for 1 cin statement. The user enters a string of numbers, and the program places them into the proper array spot.

Enter your numbers:
=> 1 23 1 35 8 -1

Then the program takes those and places them in nums 0-4. All with only prompting one cin statement.
Last edited on
I think what ne555 was saying is that you're writing into nums[k] but because the loop has incremented you're checking the element just after the one you wrote into.

Consequently, in your updated code, you're looking two elements ahead. Does that help?

-Albatross
Last edited on
Yes. I see it now.

1
2
3
4
5
6
int k = -1;
do   
{
    k++;
    cin >> nums[k];
}while(nums[k] != -1);


This is what works.
Last edited on
Topic archived. No new replies allowed.