Thread: User input being a number?

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    22

    User input being a number?

    Hi guys,
    I have a technical question. How do I see if the user's input is a number?

    So for example, when they type in 6,4 how can I get both 6 and 4 to store it in two variables?
    I tried to implement this using a if statement like so : if(input == "%d%d") but I guess it doesn't work like that.

    Help please?


    EDIT: Um, I seriously don't know why it posted twice.
    Last edited by Watabou; 03-13-2011 at 02:42 PM.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Well seeing as 6,4 is a string really...

    Code:
    char buffer[ BUFSIZ ];
    
    fgets( buffer, sizeof buffer, stdin );
    
    if ( sscanf( buffer, "%d,%d", &foo, &bar ) == 2 )
    {
       printf( "%d\n", foo );
       printf( "%d\n", bar );
    }
    Thus I think foo and bar can be used now. Have you read our FAQ, which should help you on questions like this?

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    22
    Oh thanks. Yeah I should have read the FAQ. Sorry about that.

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Watabou View Post
    Hi guys,
    I have a technical question. How do I see if the user's input is a number?

    So for example, when they type in 6,4 how can I get both 6 and 4 to store it in two variables?
    I tried to implement this using a if statement like so : if(input == "%d%d") but I guess it doesn't work like that.

    Help please?
    You already have one good suggestion but you can also try...
    Code:
    int a = 0;
    int b = 0;
    int c = 0;
    
    c = scanf(%d,%d",&a,&b);
    if (c < 2 )
      puts("One of those was not a number");
    All of this should be explained in your C library documentation. Most good compilers have relatively complete help files for just this reason.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to limit user input to a certain number of digits?
    By NewbGuy in forum C Programming
    Replies: 7
    Last Post: 05-08-2009, 09:57 PM
  2. Input statement problem
    By une in forum C Programming
    Replies: 3
    Last Post: 05-29-2007, 11:16 PM
  3. Prevent user input
    By bonne_tim in forum C Programming
    Replies: 11
    Last Post: 01-01-2007, 03:18 PM
  4. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM