Invalid code using fgets?
I wrote code that uses the fgets function with several conditions that call other functions within the code, namely aMethod and bMethod.
int main(void) {
char buffer[1024];
while (fgets(buffer, 1024, stdin)) {
if ((strcasecmp(buffer,"a")) == 0) {
aMethod();
}
if ((strcasecmp(buffer, "b")) == 0) {
bMethod();
}
}
}
I'm not sure why it is not reaching the if statements. Any help would be great, thanks.
If in doubt, print it:
int main(void) {
char buffer[1024];
while (fgets(buffer, 1024, stdin)) {
fprintf(stderr, "BUFFER is [%s]\n", buffer); /* <==== */
if ((strcasecmp(buffer,"a")) == 0) {
aMethod();
}
if ((strcasecmp(buffer, "b")) == 0) {
bMethod();
}
}
}
you will find many bugs this way.
You forgot you fgets
are using a character \n
in the buffer. Separate it using the cool function strcspn()
from string.h
. Add the if
following before the operations :
buffer[strcspn(buffer,"\n")] = 0;
otherwise you can use a familiar function strlen()
:
size_t len = strlen(buffer);
if(len > 0 && buffer[len-1] == '\n')
buffer[len-1] = 0;
You forget that you fgets()
leave the newline in the buffer (unless the input is too long). Thus, the input string cannot match any of the strings you are comparing.
Also, the C standard does not have a feature like strcasecmp()
. This is a POSIX function.