#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    21
    Rep Power
    0

    a C keyboard input question


    Hi, guys...I have a question about keyboard input in C

    let's say I have a program which allows user to type in command
    commands are in the form:
    command parameter1 parameter2...etc

    since commands have different # of parameters..I'll need to use fgets or gets to get the whole command string and parse it...

    also, I'll allow user to continue inputing command except when they type in "quit"

    this is how I do it..

    char command[100], *com;

    for(;; )
    {
    com = fgets(command, 50, stdin);
    // this line just get the whole command as a string

    if(strcasecmp(command, "quit") == 0)
    break;

    execute(com);
    // this is a function which parse the whole command string
    and execute approapriate functions...

    }

    but here comes a problem...
    if a user didn't type anything, but just hit ENTER....it'll have a segmentation fault, becuz the fgets will have some problem with nothing entered....I thought that the fgets will return NULL..so I can use that condition to detect this kind of situation and just loop around again.....but it doesn't happen that way...

    I was wondering if there's a way I can do to make my program keeps waiting for user command, even if the user decided to press a whole lot of ENTERs, it'll just loop around..

    tks....
  2. #2
  3. not a fan of fascism (n00b)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Feb 2003
    Location
    ct
    Posts
    2,756
    Rep Power
    95
    a couple things. as you said, fgets returns NULL on error, so you need to check the return value. if you read teh man pages for fgets() you will see that it returns the newline character in the input stream if there is room. so when the user just pushes ENTER, the newline character will be teh only character returned by fgets. try testing for that. :)
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    21
    Rep Power
    0
    I thought of that too...
    but the problem is when I enter "ENTER", it says segmentation fault....and the program terminated...
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    21
    Rep Power
    0
    oh shooot...actually....u r right.....
    tks a lot!!!

IMN logo majestic logo threadwatch logo seochat tools logo