Usage of fgets function in C

2019-01-26 15:45发布

One of my assignments in to write my own UNIX Shell. To receive input from the user, I am using fgets to capture the input as a string but I'm not really sure how it works. When I run:

char command[50];
fgets(command, sizeof(command), stdin);

printf("Your Command: %s", &command);
int length = strlen(command);
printf("Length of String: %d\n", length);

Lets say my the input was "exit". strlen says that the string is 5 characters long, instead of four. I want to do this:

if( (strcmp(command, "exit")) == 0 ){
    doSomething();
}

but command is never equaling the string that I want it to; its like it has an unknown character that Im not sure of. Is it the null character at the end? How do I change the if statement to check that the user input caught with fgets equals "exit"? Thanks!

7条回答
一纸荒年 Trace。
2楼-- · 2019-01-26 16:32

fgets is capturing the line break, too.

Note that you can overcome this in a few ways, one might be using strncmp:

if((strncmp(command, "exit", 4)) == 0)

which checks if only the first 4 characters of command match (though this might not be the right option for you here).

Another tactic is to check with the line break in place:

if((strcmp(command, "exit\n")) == 0)
查看更多
登录 后发表回答