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.
source to share
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.
source to share
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;
source to share