Click here to Skip to main content
15,913,722 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can we use for loop when we want user can not enter negative value


we want to restrict user to enter negative values
Posted
Updated 10-May-12 2:55am
v2
Comments
Prasad_Kulkarni 10-May-12 8:51am    
For me: Question is not clear Aliwaz, please elaborate.
nagendrathecoder 10-May-12 8:57am    
Please explain a bit, give some code snippet if you can.
Sandeep Mewara 10-May-12 8:58am    
This is not a well framed question! We cannot work out what you are trying to do/ask from the post. Please elaborate and be specific.
Use the "Improve question" link to edit your question and provide better information.
CPallini 10-May-12 9:04am    
for provides the iteration facility. What has it to do with user input validation?

The Manfred's solution :) :
C++
void WaitForPositiveInput(int& iValue)
{
  enum { eInitValue = -1, eMinValue = 0 };
  iValue = eInitValue;

  for (cin >> iValue; iValue < eMinValue; cin >> iValue);
}
 
Share this answer
 
Yes of course you can, not that it would make much sense though. You could use a for loop to loop until a non-negative number was input and then break out of the loop. Only the question would be why, why, why?

Regards,

Manfred
 
Share this answer
 
Comments
CPallini 10-May-12 9:34am    
He could also increase the original input in the for loop until he gets a positive number...
:-)
Manfred Rudolf Bihy 10-May-12 9:52am    
Which would make the input always 1 (or zero whatever) if a negative number was input, thus eliminating the need for the loop. Still a neat idea to burn some CPU cycles. ;)
CPallini 10-May-12 10:36am    
No one said 'increment' would be '+1'.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900