You enter a[i], but then you increment i to be i+1 before checking the value of a[i] again.
It's actually a bit more of a problem than just that, as you attempt to check a[1], you are accessing uninitialized data because you never initialized a[1] to a proper value before checking its value.
This would be easiest to solve by changing it to an unconditional loop w/ break
1 2 3 4 5 6 7
while (true)
{
cin >> a[i];
if (a[i] == -1)
break;
i++;
}
or add the max N as the condition,
1 2 3 4 5 6 7
while (i < N)
{
cin >> a[i];
if (a[i] == -1)
break;
i++;
}
// Here is the array of expenditures, complete with
// a maximum and a current count of expenditures
constint Maximum_Number_of_Expenditures = 10;
float expenditures[Maximum_Number_of_Expenditures];
int number_of_expenditures = 0;
// Our loop will allow us to enter zero to the maximum number of expenditures.
// (We will deal with other exit conditions inside the loop.)
// Instructions for the user before we enter the loop:
cout << "Enter up to " << Maximum_Number_of_Expenditures << " expenditures, one per line, as a dollar amount (e.g., 1.95).\n";
cout << "Press Enter twice to finish.\n";
while (number_of_expenditures < Maximum_Number_of_Expenditures)
{
// Instruct the user:
cout << (number_of_expenditures + 1) << ": $";
// Get the STRING input:
string s;
getline( cin, s );
// Are we done?
if (s.empty()) break;
// Try to convert the user’s input to a float.
float expenditure;
istringstream ss{ s };
iss >> expenditure;
if (!ss)
{
cout << "That was not a dollar amount. Try again.\n";
continue;
}
// Add the expenditure to the list
expenditures[number_of_expenditures++] = expenditure;
}
// (We asked the user to press Enter twice to exit, but if he entered the
// maximum number, we should still accept that additional Enter press.
if (number_of_expenditures == Maximum_Number_of_Expenditures)
{
string s;
getline( cin, s );
}