Program outputting 'nan'?

I am writing a cashier program to take the 'Item ID' from a user and figure out the price for that item, and then add that to the total. If they enter a negative number it will calculate the total. However, when i try and run it it works fine until i try and calculate the total, where it says

Total: $ nan

I wonder if it is something wrong with how i declared my array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>
using namespace std;
int main()
{
	float item[5] = {5,99.99,1.99, 0.99, 40}; //the numbers in curly braces are prices
	float total = 0;
	int user = 0;
	cout << "To finish purchase and calculate total, enter a negative number.\n----------------------------------\n";
	start:
	for(;user >= 0; total = total+item[user])
	{
		cout << "Item ID: ";
		cin >> user;
	}
	cout << "-----------------\nTotal: $ " << total << "\n-----------------\n";
	user = 0;
	total = 0;
	goto start;
	return 0;
}

(yes, I know, don't lecture me on using goto)
Thanks!
Last edited on
for is similar to while. In this case:
1
2
3
4
5
for ( ; user >= 0; total = total+item[user] )
{
  cout << "Item ID: ";
  cin >> user;
}

does the same as
1
2
3
4
5
6
while ( user >= 0 )
{
  cout << "Item ID: ";
  cin >> user;
  total = total + item[user];
}

Which item is added to the sum on the last iteration?
(The iteration, where the user gives a negative input.)


How about:
1
2
3
4
5
6
7
8
while ( true ) {
  float total = 0.0;
  cout << "Item ID: ";
  while ( std::cin >> user && 0 <= user && user < 5 ) {
    total += item[user];
  }
  std::cout << "-----------------\nTotal: $ " << total << "\n-----------------\n";
}

Topic archived. No new replies allowed.