Code not reaching statements using fgets?

帅比萌擦擦* 提交于 2019-12-05 21:22:39

If in doubt, print it out:

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 a lot of errors this way.

You forget that fgets() leaves the newline in the buffer (unless the entered line is too long). So the input string cannot compare equal to either of the strings you are comparing with.

Also, there is no such function as strcasecmp() in standard C. It is a POSIX function.

You forgot that fgets consumes the \n character into the buffer. Strip it off by using a cool function strcspn() from string.h. Add the following just before the if statements:

buffer[strcspn(buffer,"\n")] = 0;

or else, you could use the familiar strlen() function:

size_t len = strlen(buffer);

if(len > 0 && buffer[len-1] == '\n')
    buffer[len-1] = 0;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!