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!!!
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.
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?