reading chars with scanf

This is a discussion on reading chars with scanf within the C Programming forums, part of the General Programming Boards category; Im writing a program and in it I ask the user to enter a certain ammount of letters seperated by ...

  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
    32,855
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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, 08: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21