I expected the program below to loop only three times printing "try again"
on the third time to print " blocked"
I just don see what i did wrong. please help me out. thanx in advance.
cout<<"please enter the value of x\n";
getline(cin, MyString);
stringstream(MyString)>>x;
for(;x<10;x++)
cout<<"try again\n";
if(x==x+3)
{
cout<<"blocked\n";
}
}
if(x == (x + 3)) will always return false, because x will never equal itself plus 3, because itself is 3 less than itself plus 3 no matter what number it is.
Also: for(;x<10;x++)
You need an initialization. Because it is missing, the length of the loop can vary.
try: for(int i = 0; i < 3; i++)
That will loop 3 times no matter what.
I also recommend you put your if statement before the "try again" prompt, because if you dont, you will see "try again", and then "blocked" immediately after.
Also, I would use a bool to represent the status of 'blocked' and 'not blocked', because you have to break out of that 'for' loop eventually. After that, just 2 simple 'if' statements: 'if blocked', and 'if not blocked'.
Also, you are forgetting backets around your 'if' statement.
THINK ABOUT THE STEPS YOU WANT YOUR PROGRAM TO TAKE:
1 You want it to prompt for password 3 times.
2 you want it to show 'blocked' if the user gets it wrong 3 times.
3 you want it to allow the user access if he gets the password right at any point in the 3 tries.
in the code above, all you have to do to get blocked is enter the value of the number of tries you have done. On the first time, I enter 0 and i will be blocked, because x = i.
Hints:
put your prompt in your 'for' loop
do not put in 'if' statements comparing 'i' and 'x', because they have nothing to do with one another.