我无法理解 mgetline 在这段代码中做了什么。任何人都可以帮助我吗?
int mgetline(char s[],int lim)
{
int c, i;
for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if(c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
该函数基本上从标准输入流中逐个读取字符,stdin
直到您输入\n
(换行符)或达到s
,的数组限制lim
。字符存储在 中,char s[]
并返回读取内容的长度。
很难用更多细节来回答,因为你不明白它是什么有点不清楚,但我试图对代码进行注释以使其更清晰。
这是相同的代码,只是重新格式化以适合我的评论。
int mgetline(char s[], int lim) {
int c, i;
for(i = 0; // init-statement, start with `i` at zero
i < lim - 1 // condition, `i` must be less than `lim - 1`
&& // condition, logical AND
(c = getchar()) !=EOF // (function call, assignment) condition, `c` must not be EOF
&& // condition, logical AND
c != '\n'; // condition, `c` must not be `\n` (newline)
++i) // iteration_expression, increase i by one
{
s[i] = c; // store the value of `c` in `s[i]`
}
if(c == '\n') { // if a newline was the last character read
s[i] = c; // store it
++i; // and increase i by one
}
s[i] = '\0'; // store a null terminator last
return i; // return the length of the string stored in `s`
}
在循环condition
部分,for
您必须具备 3 个条件,true
循环才能进入语句for(...;...;...)
statement
。我已将该语句放入代码块中,以便更容易查看作用域。如果输入流 ( ) 关闭EOF
,则返回一个特殊值。getchar()
stdin
注意:如果传递一 char
( lim == 1
)的数组,此函数将导致未定义的行为。任何读取未初始化变量的程序都有未定义的行为——这是一件坏事。在这种情况下,如果lim == 1
,您将c
在循环之后读取,c
然后仍然未初始化。
要么初始化它:
int mgetline(char s[], int lim) {
int c = 0, i;
或退出函数:
int mgetline(char s[], int lim) {
if(lim < 2) {
if(lim == 1) s[0] = '\0';
return 0;
}
int c, i;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句