Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Nov 2003
    Location
    Code Heaven
    Posts
    129
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Validating Input...

    In C++ if an integer value is expected,and the user enters a character,what value shall the variable actually take?

    Code:
    int n;
    cout<<"n=";
    cin>>n;

    And also,what sort of validation is it best to use?
    For example,this won't work:

    Code:
    int n;
    do
    cout<<"Enter a number:";
    while(!(cin>>n));

  • #2
    Senior Coder Mhtml's Avatar
    Join Date
    Jun 2002
    Location
    Sydney, Australia
    Posts
    3,531
    Thanks
    0
    Thanked 1 Time in 1 Post
    Well, I hardly ever use console stuff but I believe that you can just do it like how you have done except instead of !cin>>n using cin.fail (it's a bool)..

    Code:
    int n;
    do
    cout<<"Enter a number:";
    cin>>n;
    while(cin.fail);
    As for the value the variable will take when a char is entered, I don't think it will take any value. It isn't initialized in your example so it probably has some random number in it.
    Omnis mico antequam dominus Spookster!

  • #3
    Regular Coder
    Join Date
    Nov 2003
    Location
    Code Heaven
    Posts
    129
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Hmm..well it's quite odd that !cin>>n doesn't work,it should be working coz cin returns a bool value depending on it's succes in reading the value...


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •