Thread: input problem

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    25

    input problem

    hello
    the input i need the program to interpret is:
    D#W#L#I#
    where D,W,L,I are actions and the "#" after is the amount
    now i know that the best way is to use getchar()
    and switch.

    and my question is how can i tell the program to get the # as a whole and not as indvidual digits, because the number could be any number ranging from 1- 9999999

    D,W,L,I can be in any order and variation meaning : W#D#I#I# or L#L#I#I#W#D#W#D etc...

    so i can't just put scanf(%c%d%c%d%c%d%c%d).

    thank you for your help!

  2. #2
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    1) Read everything into a string using getline.
    2) Parse the string one char at a time until you encounter a number.
    3) Use sscanf or strtol to read in the number and use the current location of the string as parameter.
    4) Repeat step 2 until EOF.
    Last edited by Memloop; 05-08-2010 at 02:35 PM.

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    25
    Quote Originally Posted by Memloop View Post
    1) Read everything into a string using getline.
    2) Parse the string one char at a time until you encounter a number.
    3) Use sscanf or strtol to read in the number and use the current location of the string as parameter.
    4) Repeat step 2 until EOF.

    thank you for your answer, but i don't know the "getline" or "sscanf" (with double s) functions. can you explain please?

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    Sorry, getline is a C++ function. I was thinking of fgets. Use strtol instead of sscanf for better error checking: strtol(3): convert string to long integer - Linux man page

  5. #5
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    555
    You could also use getchar and scanf() combined which is probably what your "professor" wants you to do, Memloop provides a more robust solution.

    Ie inside your switch, each case then calls scanf() to get the number, then the next getchar call will get the next letter and so on, of course if there is an error in the string everything will get messed up.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. geting input in C, problem in getting input
    By BujarM in forum C Programming
    Replies: 3
    Last Post: 04-17-2009, 09:38 PM
  2. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  3. Input statement problem
    By une in forum C Programming
    Replies: 3
    Last Post: 05-29-2007, 11:16 PM
  4. Problem with File Input & Pointers
    By jenna in forum C++ Programming
    Replies: 9
    Last Post: 12-04-2004, 11:34 PM
  5. Problem with text input
    By newbie in forum C++ Programming
    Replies: 2
    Last Post: 03-10-2002, 04:44 PM