Sunday, June 3, 2012

Input Validation Using While Loop and Do While Loop


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

9 comments:

  1. 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 ?

    Thanks

    ReplyDelete
    Replies
    1. Should have replied here... anyways

      Delete
  2. I have to say this post was certainly informative and contains useful content for enthusiastic visitors. I will definitely bookmark this blog for future reference and further viewing. Thanks a bunch for sharing this with us!
    Scarpin Videos

    ReplyDelete
  3. Thank you for your whole labor on this web page. I love working on research and it’s really simple to grasp why. I notice all of the dynamic mode you present both useful and interesting tricks through this blog and therefore encourage contribution from other ones on the concept.
    external hard drive recovery

    ReplyDelete
  4. Replies
    1. It change de value the next value ex: !1=0, !0=1

      Delete
  5. This comment has been removed by the author.

    ReplyDelete
  6. @mdu.
    This 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/

    ReplyDelete