Thread: reading chars with scanf

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    36

    reading chars with scanf

    Im writing a program and in it I ask the user to enter a certain ammount of letters seperated by a space (i.e: "a b c"). How can I do this while making sure the input is valid (separated by a space)?

    thanx

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    How about reading one character at a time and checking alternately for a letter and then a space?

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

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    36
    isnt there a way to format scanf and then check the return value?

    something like :
    res = scanf("/*whatever*/", ***);

  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
    Well you would use fgets() to read a line, then sscanf to validate it.

    I suppose something like
    Code:
    char buff[BUFSIZ], t1[BUFSIZ], t2[BUFSIZ], t3[BUFSIZ]
    fgets( buff, BUFSIZ, stdin );
    if ( sscanf( buff, "%s %s %s", t1, t2, t3 ) == 3 &&
        strlen( t1 ) == 1 && strlen( t2 ) == 1 && strlen( t3 ) == 1 ) {
    }
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems reading entered race times C
    By loopymoo26 in forum C Programming
    Replies: 12
    Last Post: 05-23-2009, 07:38 AM
  2. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  3. Replies: 2
    Last Post: 02-20-2005, 01:48 PM
  4. Quzah's printf and scanf tutorial...
    By quzah in forum C Programming
    Replies: 2
    Last Post: 03-20-2002, 03:59 AM
  5. scanf but not complete
    By Unregistered in forum C Programming
    Replies: 8
    Last Post: 03-10-2002, 08:26 AM