how to check if input is only positive number?

This is a discussion on how to check if input is only positive number? within the C Programming forums, part of the General Programming Boards category; id need a function which checks if the input isnt positive number and asks the user again until input is ...

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    7

    how to check if input is only positive number?

    id need a function which checks if the input isnt positive number
    and asks the user again until input is right (in C language)

    i tried many things and didnt get it to work right.


    first it should check if it isnt numeric and ask again

    then it should check if it is zero or below and ask again

    and it should work three times separately for day, month and year..

    id appreciate help...;-)

  2. #2
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    Show us your code, and we'll tell ya what's wrong with it.
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  3. #3
    Registered User
    Join Date
    Mar 2004
    Posts
    7
    my code became very difficult to understand...and it was a bad example,.I would just like to know how u guys are solving this kind of problem in general.

    Checkinf if it isnt numeric i got made, but it somehow got screwed up checking for if input is negative..(cause i used some example from the net and i quess buffers got messed up and it didn+t suite for my needs for multiple cehcks of different variables.I+d like to see a good example of doing it right way.

    of course here is the if-negative checking.

    while (days<0)
    {
    printf("Positive number required\n");
    printf("Give a Day: ");
    scanf("%d",&days);
    }

    so id need an example of how to check if the number isnt a letter or something other than a number..please help
    Last edited by hanek; 04-25-2004 at 02:31 PM.

  4. #4
    I like code Rouss's Avatar
    Join Date
    Apr 2004
    Posts
    131
    If you are reading the input as an integer, if the user enters a character, it'll be stored as it's integer equivalent.
    So if they type 'A', the number 65 will be stored in days.
    To check whether or not they entered a letter or a number. The only way I know is to use ctype functions. But then days would have to be a char. And if you want to use numbers higher than 9 you would have to use a char[].

    The ctype funtion you would want is isdigit().

    Since it sounds like you want to go for days and months and years, I'm guess days wouldn't be higher than 31?

    So you would want to declare days as a char array. Remember to a space for the '\0'.
    Ask the user to enter the number of days. Input it as a string.
    Loop through the index checking each index in isdigit().
    Code:
    for(index = 0; index < strlen(days); index++)
    if(!isdigit(days[index]))
    {
    ...Do whatever you want to do if it's not a digit...
    }
    If they are all digits, use sscanf to convert the string (char array) to an integer.
    Then do whatever you want to do with the integer.

    I hope I was wrote that clearly...
    I'm not an expert, so are there any easier ways to do this?

  5. #5
    Registered User
    Join Date
    Mar 2004
    Posts
    7
    so how does the converting work exactly....?im a newbie...also got( warning C4018: '<' : signed/unsigned mismatch) in

    for(index = 0; index < strlen(days); index++)
    while(!isdigit(days[index]))
    {
    printf("Has to be a number\n");
    printf("Give the day again: ");
    scanf("%s",&days);
    }
    i declared char days[3];
    Last edited by hanek; 04-25-2004 at 03:47 PM.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Well for starters, strlen will assume whatever you're passing it is null terminated. If not, have fun. Next, if you are indeed going to be using a string, why don't you just check the first digit, and see if it's a - character? If so, make them do it over.

    Or, why don't you just call atoi, and check to see if it returns < 0?

    At any rate, your loop is all wrong. What you're doing is basicly looping through each character in a character array, and at that point, you're calling scanf, and overwriting the string again. If you do want to make your version work, you only need something like:
    Code:
    loop until you've got a non-negative number.
        read value into days
        loop through each character
           if this character is not a digit
               break
        end loop
    end loop
    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    I like code Rouss's Avatar
    Join Date
    Apr 2004
    Posts
    131
    Yeah, I was talking about using strings for the input.

    So the scanf should be scanf("%s", days); No &.

    The conversion would be "sscanf(days, "%d", &int_var);" (notice sscanf not scanf).

    But you should probably use atoi() like quzah said. I'm basically a beginner too... And haven't used it enough to know what all it does. Besides convert a string to an integer.

    quzah - What happens if you atoi("5ff5") or something like that?

  8. #8
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Read this FAQ fully to find your answers...
    http://faq.cprogramming.com/cgi-bin/...&id=1043284385
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  9. #9
    /*enjoy*/
    Join Date
    Apr 2004
    Posts
    159
    use this to request the number
    [quote]

    int number(int*a); /* to call function use number(&variablename);
    {
    while(a<=0)
    {
    printf("write your number\01\n");
    if (a<=0) {printf("error number \n\02");}
    scanf("%i",a);
    }
    [\quote]
    }

  10. #10
    /*enjoy*/
    Join Date
    Apr 2004
    Posts
    159
    use this to request the number

    int number(int*a); /* to call function use number(&variablename);
    {
    while(a<=0)
    {
    printf("write your number\01\n");
    if (a<=0) {printf("error number \n\02");}
    scanf("%i",a);
    }

    }

  11. #11
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>while(a<=0)
    In the code a is a pointer, so your comparing it to zero in this context is probably incorrect. I guess you mean while(*a<=0)
    But then, the first time through the loop you don't know what value *a has, so you can't really use if for input comparisons anyway.

    >>scanf()
    Always check the return code from this function to see if it did what you asked it to. But then again, it won't meet the requirements, as it will fail to read any non-numeric characters in, and you'll be none the wiser.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  12. #12
    WDT
    WDT is offline
    Tha 1 Sick RAT
    Join Date
    Dec 2003
    Posts
    271
    Just to check can't you try a converse solution by restricting the types of input to the variable using a scanset??
    I haven't been doing my C for a while but
    Code:
     scanf (%[0-9], myintvar)
    may solve it. That, by logic means only decimal numbers will be read into that variable. Save you having to check for the input. (But then again I could be wrong. Double check in a text book)
    A hundred Elephants can knock down the walls of a fortress... One diseased rat can kill everyone inside

  13. #13
    I like code Rouss's Avatar
    Join Date
    Apr 2004
    Posts
    131
    WDT-
    I think that could work... You forgot the 'd' though... The only thing is, we did examples of that in class, and I didn't like it.. Not that me not liking it makes it bad, but I think it was because it would stop reading if you didn't type one of the acceptable characters... Which would be annoying... To me anyway... I think.

  14. #14
    former member Brain Cell's Avatar
    Join Date
    Feb 2004
    Posts
    472
    Here is a code that will restrict the user to enter a numeric positive number. And when he inputs what ever else , the program will ask him to input a valid number again :

    Code:
    #include<stdio.h>
    #include<stdlib.h>   /* header file for function 'strtol()' */
    
    int main()
    {
    	char input[BUFSIZ], *p;
    	long result;
    
    	printf("Please enter a positive integer : ");
    
    	for(;;){        /* infinite "for" loop */
    
    		fgets(input , sizeof(input), stdin);
    
    		result = strtol(input , &p, 10);
    
    		if(input[0] != '\n' && result > 0 && (*p == '\n' || *p == '\0'))
    			break;
    		else
    			printf("Invalid input !\n\nPlease enter a positive integer : ");
    			result = 0;
    
    			}
    
    		printf("You've entered the number %ld", result);
    
    	return 0;
    }
    You said you are a newbie so im not sure if you're going to understand the previous code. Its worth studying though. I've learned that method from here :

    http://faq.cprogramming.com/cgi-bin/...&id=1043284385

    (see last part of option 3).


    hope this help...
    My Tutorials :
    - Bad programming practices in : C
    - C\C++ Tips
    (constrcutive criticism is very welcome)


    - Brain Cell

  15. #15
    Registered User
    Join Date
    Mar 2004
    Posts
    7
    well, thank u for the the huge amount of help...i also got a link to an example in the net from a friend.Ill try these as soon as i got enough time.....here s the link and the example.

    http://www.physics.ohio-state.edu/~n...input_in_C.pdf

    The following code fragment shows how we might use the return from sscanf to request
    input until were satisfied with the response:
    Code:
    line char[100]; /* a line to be read from the terminal */
    int answer; /* an integer chosen by the user */
    answer = -1; /* set answer to a value that falls through */
    
    while (answer != 0) /* iterate until told to move on */
    {
         printf ("\nSample menu:\n");
         printf (" [1] Do something");
         printf (" [2] Do something else");
         printf ("\nWhat do you want to do? [0 for nothing] ");
        
         fgets (line, sizeof(line), STDIN); /* read in a line */
        sscanf_result = sscanf (line, "%d", &answer); /* get answer */
        if ((sscanf_result == 0) | (sscanf_result == EOF))
    {
    /* either a non-integer entered or an end-of-line */
    printf ("\n *** You have to enter an integer! ***\n");
    answer = -1; /* set answer to a value that falls through */
    }

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Not working in linux...
    By mramazing in forum C++ Programming
    Replies: 6
    Last Post: 01-08-2009, 02:18 AM
  2. allegro issues
    By mramazing in forum C++ Programming
    Replies: 1
    Last Post: 01-07-2009, 11:56 PM
  3. xor linked list
    By adramalech in forum C Programming
    Replies: 23
    Last Post: 10-14-2008, 11:13 AM
  4. Input statement problem
    By une in forum C Programming
    Replies: 3
    Last Post: 05-30-2007, 12:16 AM
  5. Random Number problem in number guessing game...
    By -leech- in forum Windows Programming
    Replies: 8
    Last Post: 01-15-2002, 05:00 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21