Code not reaching statements using fgets?

安稳与你 提交于 2020-01-02 08:38:00

问题


I have written code that uses the fgets function with multiple 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 doesn't reach the if statements. Any help would be great, thankyou.


回答1:


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.




回答2:


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.




回答3:


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;


来源:https://stackoverflow.com/questions/29875285/code-not-reaching-statements-using-fgets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!