Thread: Help with inputs

  1. #1
    Registered User
    Join Date
    Mar 2010

    Help with inputs

    I have a very simple code problem.

    #include <stdlib.h>
    #include <stdio.h>
    int main (){
        int r, c;
        while (1){
              printf ("Indicate the size of the play board (must be even numbers between 4-20)\nEnter row column: ");
              scanf ("%d %d", &r, &c);        
              if (((r%2) == 0)&& ((c%2)==0)&&(c>=4)&&(c<=20)&&(r>=4)&&(r<=20))
                  printf ("Invalid input. \n\n");
              _sleep (500);
        return 0;
    Basically i want even numbers between 4-20, and asks again if its not.
    However when i enter a symbol, it goes haywire, and it doesn't ask the user and just loop itself.

    Why is this and how do i fix this?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    The f in scanf means "formatted". If your input isn't formatted, then scanf isn't for you. (That is to say, if you don't trust your users to not type letters, then you are going to have to read things in by characters and build the number yourself.)

  3. #3
    Registered User
    Join Date
    Mar 2010
    I see! Thanks alot ! I will use getchar instead

  4. #4
    Registered User
    Join Date
    Apr 2006
    You can check the return of scanf. If it is 0, then you know that scanf could not read any numbers. However, you will still have to read in the bogus input, before retrying scanf.

    A common approach is to use fgets to read each line, then sscanf to parse it. If a line does not parse right, then you can print an error and retry.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 02-22-2010, 11:52 PM
  2. How do I validate these inputs?
    By Kyeong in forum C Programming
    Replies: 1
    Last Post: 10-19-2008, 02:20 PM
  3. checking inputs meets multiple conditions
    By 60beetle60 in forum C Programming
    Replies: 5
    Last Post: 04-19-2008, 08:25 AM
  4. Taking inputs at Command Line
    By Stephenf in forum C++ Programming
    Replies: 1
    Last Post: 09-28-2005, 02:33 AM
  5. Getting multiple inputs using cin
    By edk in forum C++ Programming
    Replies: 2
    Last Post: 09-13-2001, 02:34 PM

Tags for this Thread