3

I've looked up the functions in the manual, but I still don't get this. According to the person who wrote the code, if the User enters "y" then the function (not shown here) will execute. However, because of the !, it looks to me like the function (not shown here) will execute if the user enters something other than "y".

Please explain (I"m a relative newbie so as much detail as possible would be helpful). Thanks

if(!strncasecmp(trim(fgets(STDIN)),'y',1)) 
2
  • Is this in the context of a command line application? Commented Jun 3, 2011 at 9:05
  • yes, the script is creating a shell tool Commented Jun 3, 2011 at 9:07

2 Answers 2

10

fgets(STDIN) - reads a string from standard input(keyboard in your case).

trim - removes any spaces surrounding the user input. So if the user enters ' y' or a 'y ', it'll be converted to 'y'

strncasecmp - The user might enter either uppercase Y or lowercase y, this function helps you to compare case insensitive way. Also this function returns 0 if the comparison is successful and then you use the ! (not operator) which changes the 0 to a 1 so that the if test passes.

You could re-write it as:

if(strncasecmp(trim(fgets(STDIN)),'y',1) == 0) 
Sign up to request clarification or add additional context in comments.

Comments

4

The function strncasecmp returns 0 if there is no difference between the strings compared, hence the ! to check if they're equal.

1 Comment

Yes. Many string comparison functions in a variety of languages/libraries return like this, for sorting purposes -- negative value if the string is "less" than the comparison string, positive value if it's "more" than the comparison string, zero if equal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.