473,842 Members | 1,622 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Validating User Inputs

2 New Member
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 2565
Hunderpanzer
60 New Member
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
Wizard1981
11 New Member
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 Recognized Expert Contributor
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 Recognized Expert Moderator Expert
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
supernick
2 New Member
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 Recognized Expert Specialist
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 Recognized Expert Moderator Expert
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
3940
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 validated using the TEXTn_validate event but I would like to stop the user before it gets that far.
2
5206
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 for all invalid input. Just for example, if user inputs 'abc' an error is caught, but if user inputs '432' the program hangs. Any clarification appreciated. Thanks, Bill
5
2454
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) { } Now , i want to know should I validate all the inputs before i start using
0
2441
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 (http://support.microsoft.com/kb/810852), but then I realized that the hotfix mentioned was in .Net v1.1, which I am using. I took the sample from that article and recreated the situation I see in my application. (Code included below.) If you run the...
6
1929
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) and no whitespace or punctuation marks. Thanks
21
4523
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 websites such as planet-source-code.com, but my search has been in vain. Can someone please help me out. Or at least, point me in the right direction? Thank you very much. :)
3
2802
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
836
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 box is set to "TRUE" because this info needs to be remembered (using session variables) when the user returns to the "Create New Quote" page and the data is used for other pages as well. My two issues: 1) I am now trying to validate the text...
3
2180
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 onchange/on blur to activate a javascript function to check the input for correctness once user moves out of the input box (tab or mouse click). If it looks OK, then nothing happens. But if an error is detected, the function puts out an alert box...
0
9875
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10945
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10614
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10674
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10317
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7859
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7040
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4500
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4090
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.