473,387 Members | 1,799 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Validating User Inputs

Basically i have this task to get 2 inputs stored into num1 and num2 of int type. The program will then list all the possible numbers from 0 to num1, which are divisable by num2.

So if my input is 10 and 2
my output should be 2 4 6 8.

the problem now is that if i type in negative value or a character i won't get a correct output.

so i came up with this validation :

Expand|Select|Wrap|Line Numbers
  1. if(num1 < 0 || num1==NULL){
  2. printf("enter a number greater than 0");
  3. return 0;
  4. }
  5.  
which is not efficient at all. cause instead of re-prompting for another input of num1, it just exits. and if it is NULL a different message should be printed. like "Please enter in a number".

Is there a solution to this? assuming that you only know arrays, pointers, and conditions, and the only lib you know of is stdio.
Aug 15 '07 #1
7 2540
Basically i have this task to get 2 inputs stored into num1 and num2 of int type. The program will then list all the possible numbers from 0 to num1, which are divisable by num2.

So if my input is 10 and 2
my output should be 2 4 6 8.

the problem now is that if i type in negative value or a character i won't get a correct output.

so i came up with this validation :

Expand|Select|Wrap|Line Numbers
  1. if(num1 < 0 || num1==NULL){
  2. printf("enter a number greater than 0");
  3. return 0;
  4. }
  5.  
which is not efficient at all. cause instead of re-prompting for another input of num1, it just exits. and if it is NULL a different message should be printed. like "Please enter in a number".

Is there a solution to this? assuming that you only know arrays, pointers, and conditions, and the only lib you know of is stdio.


Well supernick I have a Temporary solution for you, although I've been informed from experts on this exact site that it's not a correct thing to do, I've had this problem myself and it's the only thing I found that has worked.

This is temporary until someone corrects me and / or you find a better way.

You can use goto to call back right before the prompt if the conditions are met .


so first you put an identifier? right before the prompt which can be almost anything (dog in this example) followed by a colon

Expand|Select|Wrap|Line Numbers
  1. dog:
  2. cout << "Enter a number ";
  3. cin >> num1;
  4. if(num1 < 0 || num1==NULL){
  5. printf("enter a number greater than 0");
  6. goto dog;
  7. }
then continue with the code.
code in bold is what I added.
Aug 15 '07 #2
In order to omit the "goto", it's better to use a while-loop:
Expand|Select|Wrap|Line Numbers
  1. bool validInput = false;
  2. while(!validInput)
  3. {
  4.     cout << "Enter a number greater than 0 ";
  5.     cin >> num1;
  6.     if(num1 > 0) validInput = true;
  7. }
Aug 15 '07 #3
ilikepython
844 Expert 512MB
In order to omit the "goto", it's better to use a while-loop:
Expand|Select|Wrap|Line Numbers
  1. bool validInput = false;
  2. while(!validInput)
  3. {
  4.     cout << "Enter a number greater than 0 ";
  5.     cin >> num1;
  6.     if(num1 > 0) validInput = true;
  7. }
Yes, the loop is a much better solution than a goto. Pretty much anything with gotos can be accomplished without them. They should be avoided.
Aug 15 '07 #4
weaknessforcats
9,208 Expert Mod 8TB
No one is taking any notice of bad input. That is, the fail bit is not considered.

A better solution is:
Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.      int test;
  4.      bool rval;
  5.      while (1)    //infinite loop. Need CTRL+C to stop program
  6.      {
  7.          rval = GetInt(test);
  8.          if (rval)
  9.          {
  10.              cout << "The integer is: " << test << endl;
  11.          }
  12.          else
  13.          {
  14.              cout << "Error! Eating an input character" << endl;
  15.              //You could use cin.get() here to see what you ate
  16.              cin.ignore();
  17.          }
  18.  
  19.      }
  20.  
  21.      return 0;
  22.  
  23. }
  24.  
  25. bool GetInt(int& data)
  26. {
  27.     cin >> data;
  28.     if (cin.good())
  29.     {
  30.       return true;
  31.     }
  32.     else
  33.     {
  34.         cin.clear();    //clear the fail bit that got us here
  35.         return false;
  36.     }
  37. }
  38.  
Here all of the displays are in main(). Putting displays inside functions is a bad idea as it scatters the screen layout throughtout the program. This acts like a kind of glue that prevents the functions from being used in other programs.

Here, GetInt() returns true only if an int has been entered. If an int is not entered, no corrective action is taken since the corrective action (like eating the offending character) may not eb the same in all programs. It is left to someone else to adjust the input buffer.
Aug 15 '07 #5
Thank you for all your suggestions!

The main problem about C is that they don't have boolean types. It is huge barrier for me since I come from a java background. But they do have ways to validate true and false which requires the use of 0s and 1s. so i'm assuming the equilivant of loop is

Expand|Select|Wrap|Line Numbers
  1. int validinput=0
  2.  
  3. while(validinput==0){
  4.  
  5. printf("enter a number ");
  6. scanf("%d",&userinput);
  7.  
  8. if(userinput >0 || userinput != null)
  9.     validinput =1;
  10. else
  11.     validinput=0;
  12. }
  13.  
most of the suggestions are checking for negative/null values. but how would you validate character inputs?

Finally, for the last suggestion. i'm not pretty sure what does cin.good() do? does it work for C programming as well?

Thanks for all your time!
Aug 16 '07 #6
Ganon11
3,652 Expert 2GB
No, cin.good() is a function of cin, which is the standard input for C++. In C the common input is scanf. You can still test to see if it failed, however, using the following trick. scanf returns an int value, which is the number of values it correctly read for ending. So you can check to see if both values were read correctly by catching scanf's return value and comparing it to 2 - if equal, both values were legitimate integers, and you can proceed to check if they are negative or not.
Aug 16 '07 #7
weaknessforcats
9,208 Expert Mod 8TB
The main problem about C is that they don't have boolean types.
Of course C has boolean types:

typdef short BOOL;

Now you have a BOOL.

Then you can:

BOOL x = TRUE;


and off you go.
Aug 16 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

13
by: David Gray | last post by:
Greetings all, Quick newbie type question: I would like to be able to trap non-numerical data entered into a textbox via CTRL+C and/or Shift+Insert. I realise that this data can be...
2
by: bildad | last post by:
The following 'book example' of validating input seems to be incomplete. Since it is a beginner's book it may be intentional for simplicity. But I would like to know how to make this program work...
5
by: sourabh | last post by:
Hi I have a basic qus. I am writing a middle-tier component. I have constructor which takes 3 inputs, here's how it looks internal ClassName(Database dbToUse, Int64 pk,DateTime Date) { } ...
0
by: Gary Shell | last post by:
I am experiencing some strange behavior between a UserControl's validating event and a treeview control. Initially, I thought it was related to an issue in the Knowledgebase article 810852...
6
by: J Huntley Palmer | last post by:
What is the most efficient way to validate an input to conform to your needs? I need to make sure an input is a contiguous string with only printable characters (english alphabet+numbers only)...
21
by: gurdz | last post by:
Does anyone know how to perform data validation in C? I have searched google for every possible result, and I either end up with data validation for C++ or nothing at all. I have also searched...
3
by: TheSteph | last post by:
Hi Experts ! I have a Winform Program in C# / .NET 2.0 I would like to ensure that a value in a TextBox is a valid Int32 when user get out of it (TextBox loose focus)
0
by: Mel | last post by:
I have a "Create New Quote" webpage where the user inputs a bunch of text boxes (customer name, ship to address 1 & 2, city, state, zip, etc.). Currently the "AutoPostBack" property on EVERY text...
3
by: Louis | last post by:
I have a form with multiple input boxes. I want to validate each input box (and force user to correct it) before allowing user to move to another, either using tab key or a mouse click. I try...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.