September 19th, 2003, 01:47 AM
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, *com;
com = fgets(command, 50, stdin);
// this line just get the whole command as a string
if(strcasecmp(command, "quit") == 0)
// 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..
September 19th, 2003, 02:21 AM
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. :)
September 19th, 2003, 02:46 AM
I thought of that too...
but the problem is when I enter "ENTER", it says segmentation fault....and the program terminated...
September 19th, 2003, 02:50 AM
oh shooot...actually....u r right.....
tks a lot!!!