Thread: input check

  1. #1
    Registered User
    Join Date
    Apr 2018
    Posts
    14

    input check

    hello,
    so far I've been writing codes to take in numbers and make sure the input is within a given range, yet how can I use an array or a string to make sure the input the user has typed in is indeed an integer..
    for example:
    when the user types in "a" or " a 4" I want the program the ask for a new input.. but " 10 " or " +10 " is ok.
    any ideas?
    thanks in advance..

  2. #2
    Registered User
    Join Date
    Jun 2017
    Posts
    157
    One way is to check the return value from scanf:
    Code:
    int num;
    if (scanf("%d", &num))
    {
      puts("Valid input");
    }
    else
    {
      puts("Invalid input");
    }

  3. #3
    Registered User
    Join Date
    Apr 2018
    Posts
    14
    Quote Originally Posted by OldGuy2 View Post
    One way is to check the return value from scanf:
    Code:
    int num;
    if (scanf("%d", &num))
    {
      puts("Valid input");
    }
    else
    {
      puts("Invalid input");
    }
    but this code will allow inputs such as "4 a" or "-5"
    my thought would be to read a string from the user and then check the string for any mistakes.. I just have no idea how to do that..
    I want it to read for example : " 4 a"
    and check each character.. if it sees a character that's not a number, a plus sign or a space then the valid will be input.. also a number then space then number again should be invalid " 1 0"

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Use fgets to read a whole line.
    You can then parse the string however you like.

    > One way is to check the return value from scanf:
    Your code would also claim EOF as success.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Dec 2011
    Location
    Namib desert
    Posts
    94
    The header-file ctype.h shows a whole lot of character handling functions.
    Or have a look here: The GNU C Library

  6. #6
    Registered User
    Join Date
    Apr 2018
    Posts
    14
    Quote Originally Posted by Salem View Post
    Use fgets to read a whole line.
    You can then parse the string however you like.

    > One way is to check the return value from scanf:
    Your code would also claim EOF as success.
    I'm sorry. could you elaborate on how to check the string input.. I don't quite get how to work with strings

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Like so
    Code:
    char buff[BUFSIZ];
    while ( fgets(buff,BUFSIZ,stdin) != NULL ) {
        if ( buff[0] == 'a' ) {
            if ( sscanf(&buff[1],"%d",&num) == 1 ) {
                // success, do command 'a' with num
            } else {
                // expected integer
            }
        } else if ( ... ) {
            // test more letters
        } else {
            // unknown command
        }
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Registered User
    Join Date
    Apr 2018
    Posts
    14
    Quote Originally Posted by Salem View Post
    Like so
    Code:
    char buff[BUFSIZ];
    while ( fgets(buff,BUFSIZ,stdin) != NULL ) {
        if ( buff[0] == 'a' ) {
            if ( sscanf(&buff[1],"%d",&num) == 1 ) {
                // success, do command 'a' with num
            } else {
                // expected integer
            }
        } else if ( ... ) {
            // test more letters
        } else {
            // unknown command
        }
    }
    Any idea why this won't work?
    Code:
    char row[258], col[258];	int nrow = 0, ncol = 0, i ;
    
    
    
    
    	while (nrow == 0 && row != NULL)
    	{
    		i = 0;
    		printf("Insert number of rows (1-50): ");
    		gets(row);
    			
    			if (row[i] != ' ' && row[i] != '+' && row[i] != '/t' && row[i] != '0' - '9'){ 
    				printf("invalid input\n"); continue; 
    			}
    			
    			if (row[i] == '+') { 
    				if (row[i + 1] != ('0' - '9')) { printf("invalid input\n"); continue; }
    			}
    			
    			if (scanf(row, "%d", &nrow) != 1){ 
    				nrow = 0;
    				printf("invalid input");
    				continue;
    			
    			}
    			printf("input is vaild\n"); i++;
    
    
    
    
    		}
    the restricitions are : user can enter as many spaces or '0' as they want if the user input '+' then a number must follow with no space, if the user enters a digit then another digit or '\n' must follow.
    to tackle the "4 4" example it's possible to check if scanf == 1, to tackle any other character rather then a number, space or '+' I used the first if.. but still it doesn't work

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    I don't know why you keep digging such large holes in the wrong place.

    1. Never EVER use gets().

    2. What is going on here?
    > if (row[i] != ' ' && row[i] != '+' && row[i] != '/t' && row[i] != '0' - '9')
    - Tabs are \t, not /t
    - You don't compare a range of values using the - operator.

    3. What is the purpose of i ?
    printf("input is vaild\n"); i++;
    I mean, you increment it for each line of input.
    You read a line, i is 0
    You read a line, i is 1
    You read a line, i is 2

    4. while (nrow == 0 && row != NULL)
    row is an array, it will always compare as not equal to NULL.

    5. if (scanf(row, "%d", &nrow) != 1)
    Note that I used sscanf(), not scanf().
    - scanf reads from stdin
    - sscanf reads from a string.


    > the restricitions are : blah blah blah blah
    Yeah, whatever.
    Stop trying to solve the WHOLE problem in one code iteration. You're never going to make it work like that unless you have infinite monkeys.

    Read this
    A development process

    It seems to me that the first letter can be
    - a space
    - a +
    - a digit in the range 0 to 9.

    In which case, your starting code should be
    Code:
    while ( fgets(buff,BUFSIZ,stdin) != NULL ) {
      if ( buff[0] == ' ' ) {
        printf("Found space\n");
      } else
      if ( buff[0] == '+' ) {
        printf("Found +\n");
      } else
      if ( isdigit(buff[0]) ) {
        printf("Found digit\n");
      } else {
        printf("Oops, invalid start\n");
      }
    }
    Make sure something like this WORKS before you proceed to next part of the problem.

    I'll say it again, learn how to break problems down into small easily understood and achievable steps.
    Simply looking at a whole paragraph of words and attempting to bash the code in a single attempt will NOT work.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    I think too many recent posters are using the infinite monkey solution method Infinite monkey theorem - Wikipedia

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. input check
    By fatsrir in forum C Programming
    Replies: 2
    Last Post: 05-06-2010, 02:37 PM
  2. Check input!
    By johnybe in forum C Programming
    Replies: 2
    Last Post: 11-09-2009, 11:58 AM
  3. help with input check
    By negevy in forum C Programming
    Replies: 1
    Last Post: 09-02-2005, 07:14 AM
  4. Input check
    By Extol in forum C++ Programming
    Replies: 2
    Last Post: 02-15-2003, 11:31 AM
  5. how do you check to see if input is an int?
    By pkananen in forum C++ Programming
    Replies: 10
    Last Post: 02-20-2002, 04:57 PM

Tags for this Thread