Thread: safe integer input

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    60

    safe integer input

    I read that the scanf function is not safe. I made an attempt for a getInt(), but I'm not happy about it. I have to give two arguments: the max value and the max length of the number (I mean the max number of characters in the string). I'm not able to extract this maxLength from the max value:

    Code:
    int getInt(int max, int maxLength){
    
    	char input[maxLength];
    	char c;
    	int i;
    	printf("Enter an integer: ");
    	for (i = 0;(c = getchar())!='\n';++i){
    			if (i < maxLength-1){
    				if (!isdigit(c) && (c !='-')){
    					printf("Number contains non-digit characters. Exiting.");
    					exit(0);
    				}
    			input[i] = c;
    			} else {
    				printf("Number was too long. Exiting");  
    				exit(0);
    			}
    	}
    	int result = atoi(input);
    	if (result <= max){ 
    		return result;
    	} else {
    		return -1;
    	}
    }
    It's kinda messy, but I don't see an alternative... Any suggestions?

  2. #2
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Your question is not clear to me. But my personal suggestion would be to use scanf() for inputting ints. It is generally not safe for inputting strings.
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  3. #3

  4. #4
    Registered User
    Join Date
    Nov 2009
    Posts
    60
    Quote Originally Posted by BEN10 View Post
    Your question is not clear to me. But my personal suggestion would be to use scanf() for inputting ints. It is generally not safe for inputting strings.
    What happens if i enter a letter instead of an integer number? The program doesn't complain, it just takes the wrong integer.

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int main(){
    	int a;
    	printf("Enter integer: ");
    	scanf("%d", &a);
    	printf("The integer was %d.\n", a);
    	return 0;
    }

  5. #5
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    If you have input you need to validate, first read it in as a string and then use strtol to convert it to an integer (see the link above). scanf doesn't handle integer overflows for example, so it's not reliable to use when dealing with user input.

  6. #6
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Quote Originally Posted by hilarius View Post
    What happens if i enter a letter instead of an integer number? The program doesn't complain, it just takes the wrong integer.

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int main(){
    	int a;
    	printf("Enter integer: ");
    	scanf("%d", &a);
    	printf("The integer was %d.\n", a);
    	return 0;
    }
    In that case you can check the value returned by scanf. scanf() returns the number of correct inputs. Eg.
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int main(){
    	int a,x;
    	printf("Enter integer: ");
    	x=scanf("%d", &a);
                    if(x==1)
    	printf("The integer was %d.\n", a);
                    else
                    printf("Input is not an integer");
    	return 0;
    }
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  7. #7
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Quote Originally Posted by Memloop View Post
    scanf doesn't handle integer overflows for example, so it's not reliable to use when dealing with user input.
    Hmmmmmmm.......you're right. This is the point where scanf fails.
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It's not really failing. You're not using it right. You can't type 100000000000000 and expect it to fit in one byte. The same goes for a 32 bit int. Use the right datatype, or don't, and just use strings for "numbers".
    Code:
    while input
        read char
        if char = sign and no stored digits
            if sign indicator not set
                set sign indicator
            else
                error
        else
        if number
            if number length ok
                store character
                increment current length conter
            else
                error
        else
        if you are doing decimal points and it is a decimal point
            if you don't have one yet
                set have decimal point
                store decimal point
            else
                error
        else
            error
    Something like that.


    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    Don't forget to include stdlib.h if you're going to use strtol. For some reason, GCC didn't warn me when using strtol without including stdlib.h, but instead resorted to returning -1 as the return value from strtol regardless of the input.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Memloop
    Don't forget to include stdlib.h if you're going to use strtol. For some reason, GCC didn't warn me when using strtol without including stdlib.h, but instead resorted to returning -1 as the return value from strtol regardless of the input.
    That could be the result of an implicit declaration defaulting to int. You could try enabling a higher warning level, e.g., -Wall.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with function for safe input.
    By Subsonics in forum C Programming
    Replies: 5
    Last Post: 11-01-2009, 02:28 PM
  2. how do i ensure a correct integer input
    By csonx_p in forum C++ Programming
    Replies: 11
    Last Post: 09-18-2008, 12:19 PM
  3. newbie programmer - needs help bad.
    By hortonheat in forum C Programming
    Replies: 17
    Last Post: 10-20-2004, 05:31 PM
  4. Reading the input file into integer arrays
    By supaben34 in forum C++ Programming
    Replies: 3
    Last Post: 12-06-2002, 07:04 PM
  5. Reading input as an integer
    By n0de in forum C++ Programming
    Replies: 4
    Last Post: 04-11-2002, 06:52 PM