Input Validation Using While Loop and Do While Loop
Looping is also used for input validation. Input validation is a process where you check whether the user is inputting the valid data or not. A user may input anything and that can make the program to behave unexpectedly.
For eg. If you create a program that takes various subject's marks as input from user and then calculates and displays total and average of those marks. Suppose that every subject was of 100 marks and so the student can score anything from 0 to 100. So if the user starts inputting more than 100 marks or less than 0 marks then the result of this will be unexpected.
The user may do mistake unintentionally or intentionally. If he does unintentionally then we should show him his mistake and then tell him to correct it . If he does intentionally then he will see that our program is smart enough to understand his mistakes.
Input validation is also necessary for security reasons as well and it can be very lengthy in real world programs, where each input is tested with various conditions.
However, here i present you some easy programs to make you understand how we can make use of while and do while loop for input validation. The below three programs will accept input from user only if the numbers are from 1 to 9. Greater than 9 and less than 1 will not be accepted. To understand these programs, you must know The Difference Between While Loop And Do-While Loop
/* A c++ program example that uses while loop for input validation */
// Program 1
#include <iostream>
using namespace std;
int main ()
{
int number;
cout << "Enter a number from 1 to 9: ";
cin >> number;
while (! (number >=1 && number <= 9 ))
{
cout << "Invalid Input. Try Again." << endl;
cout << "Enter a number from 1 to 9: ";
cin >> number;
}
cout << "Your Input Is Valid." << endl;
return 0;
}
/* A c++ program example that uses do-while loop for input validation */
// Program 2
#include <iostream>
using namespace std;
int main ()
{
int number;
do
{
cout << "Enter a number from 1 to 9: ";
cin >> number;
if (! (number >=1 && number <=9 ))
{
cout << "Invalid Input. Try Again." << endl;
}
} while (! (number >=1 && number <=9 ));
cout << "Your Input Is Valid." << endl;
return 0;
}
/* A c++ program example that uses do-while loop with data-type bool for input validation */
// Program 3
#include <iostream>
using namespace std;
int main ()
{
int number;
bool isValid = false;
do
{
cout << "Enter a number from 1 to 9: ";
cin >> number;
isValid = ( number >=1 ) && ( number <=9 );
if (isValid)
{
cout << "Your Input Is Valid." << endl;
break;
}
else
{
cout << "Invalid Input. Try Again." << endl;
}
} while (!isValid);
return 0;
}
Explanation And Clarification
while (! (number >=1 && number <= 9 )) can also be written as:while (! (number > 0 && number < 10 ))
Since, 'greater than zero' is same as 'greater than or equal to 1'.
And, 'less than 10' is same as 'less than or equal to 9'.
The above while loop condition was written using AND with NOT operator. It can also be written using OR operator and will work same as above.
while (number <= 0 || number >=10 )
OR
while (number < 1 || number > 9 )
Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.
Want to learn more? View List Of All Chapters
I tried the first example, and whether I input a char, the program go to an infinite loop. I debug the program and I had observed that integer variable is set with a negative random number and that "cin >> number" is skipped. I use MSVC10. What is the explanation of this ?
ReplyDeleteThanks
This comment has been removed by the author.
ReplyDeleteIt change de value the next value ex: !1=0, !0=1
Delete@mdu.
ReplyDeleteThis state is not catered by this post. If a user inputs a character in an integer stream, infinite loop occurs and the program crashes. Here is a post that i found very useful on internet on this topic.
http://codingmash.com/2012/06/input-validation-in-c/
how can i write a program that inputs the grade of a students in four periods and print "PASSED"if letter grade is A,B and C and"FAILED" if letter grade D and E, otherwise invalid. ( greater than or equal to 80 #A) (less than 90 but greater than or equal 80 #B) (less than 80 but greater than or equal 75 #C) (Less than 70 but greater than or equal to 60 #D) (less than 60 #E).... KINDLY HELP ME TO code this #I am a freshmen on this #programing course!!
ReplyDeleteYou could very easily use a switch statement to accomplish this.
DeleteDownload Islmic books here :http://islamicmsg.org/index.php/kutub/eedarey-ki-kutub/215-aahadees-e-mutariza-aur-un-ka-hal
ReplyDeleteThanks for your ideas. You can also find the details on Affity Solutions, at the C++ Developers. The main object of the Affity Solutions is to provide quality web services and is among the few software development company in Nagpur.
ReplyDeleteThanks for sharing Ideas.
ReplyDeleteThanks for sharing Ideas .....
ReplyDeleteWhat is Diamond problem?
ReplyDeleteThanks for sharing different validation ideas with us
ReplyDeleteweb development company LUCKY TECH
Very Useful Post!Thanks!
ReplyDeleteC++ Programming
Many of the C++ programs utilize the functionality of the while loop in making the conditions for certain inputs. This loop returns the function to the calling point whenever the user enters a value rather than the one in the given interval. I love the way the blogger has explained the C++ while loop use in such simplicity. Write my Business school Entrance Essay
ReplyDeletePkjazba Provides Fashion Makeup Hairstyle Digests Recipes Fitness Health
ReplyDeletePkjazba.com
Fine method of telling, and enjoyable article to acquire factual statements.
ReplyDeletetutorial on c++
c++ programming examples
ReplyDeleteDemonstrating copying constructors
nice c++ course thanks for share..
ReplyDeletewhere from you learn these awesome ?
ReplyDeleteudemy courses free download
Interesting Information, Keep it up
ReplyDeletenice information for beginners.thank you.
ReplyDeletelearn c++ do while loop
Great post and info.
ReplyDeleteBest Bridal Furniture Designs
Machine learning services are the future of the IT industry and one must learn these services to be competitive in the IT industry. You can click here to learn more about machine learning services and enhance your knowledge.
ReplyDeleteNice Post....It will be helpful for beginner Student.Here is a blog for C++ Programming.
ReplyDeletegreat , you can also see this
ReplyDeletemobile development