用C与fgets函数的用法

用C与fgets函数的用法

本文介绍了用C与fgets函数的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个任务在写我自己的Unix外壳的。要接收来自用户的输入,我使用与fgets捕捉输入作为一个字符串,但我真的不知道它是如何工作。当我运行:

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);

比方说我输入的是退出。 strlen的说,该字符串是5个字符,而不是四个。我想这样做:

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();
}

但命令是从来没有追平字符串,我希望它;它像它有一个未知字符林不知道的。它是在最后的空字符?如何更改if语句来检查补时与fgets用户输入等于退出?谢谢!

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!

推荐答案

与fgets 认为该行结束符作为一个有效的字符。这是您收到额外的字符。

fgets considers the line terminator as a valid character. That's the extra character you are receiving.

就做类似命令[strlen的(命令) - 1] ='\\ 0'; 来删除行终止符。然后,你可以自由地做你的。

Just do something like command[strlen(command) - 1] = '\0'; to remove the line terminator. Then you are free to do all your strcmp's.

这篇关于用C与fgets函数的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:03