In this program i am trying to enter snack codes and reject codes that are greater or equal to 100. I first had cin as cin>> snack[count];.It iterates 10 times but when i enter a number over 100 or 100, it takes it. I also tried taking the if statement out of the for loop braces and place it outside,and the same happened.
#include <iostream>
usingnamespace std;
int main()
{
constint HEALTHYSNACKS = 10;
int snack[HEALTHYSNACKS],snackcode;
for (int count = 0; count < HEALTHYSNACKS; count++)
{
cout << "Please enter the code for each snack.";
cin >> snackcode;
if (snackcode >= 100)
{
"All snack codes are under three digits. Try again.";
}
}
cin.get();
return 0;
}
CodeMonkey what's wrong? *takes deep breath* He's correct I don't get what you don't get and it's probably because you don't get what he is getting which I get to get because I get it, and I get it because I've got to get what I can get which can get got from being gotten.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
for (int count = 0; count < HEALTHYSNACKS; count++)
{
cout << "Please enter the code for snack number: "<<count;
cin >> snackcode;
cout<<"\n";
if (snackcode >= 100)
{
cout<<"All snack codes are under three digits. Try again.";
count--;
}
else {
snack[count] = snackcode;
cout<<"snack["<<count<<"] now contains : "<<snackcode;
}
}
The reason it didn't work for you previously, you might have slipped past it, is because of the fact that cin was taking and assigning the input regardless of whether it was a proper input or not, you only checked if it was proper AFTER the input. So assigning after the if condition would make it work like you wanted. ;)
You were not very wrong it's fine, just small things which you will get used to. :D
Oh and also in the snippet you posted, you didn't get the if statement to "go through" because you hadn't even written cout! ;p