c - 谁能告诉我mgetline在做什么?我无法理解
问题描述
我无法理解 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
此函数将导致未定义的行为。任何读取未初始化变量的程序都有未定义的行为——这是一件坏事。在这种情况下, if 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;
推荐阅读
- java - 在测试包的 *root* 中找不到 *-tests.jar 文件
- ruby-on-rails - 如何使用 Rails 5.2 和 Faraday gem 构建复杂的 json 以 POST 到 Web 服务?
- r - R:尝试计算均值和 sd + 警告,当对象在数据帧头中列出时找不到对象
- release-management - 在 Proget 中发布管理预发布包
- javascript - Workbox Webpack 插件 InjectManifest 构建错误
- output - 系统找不到指定的路径:'C:/Users/zeenat/Desktop/Data Science Intern/Project/Audio/neutral' 为什么会出现这个错误?
- c++ - 使用 Mingw-w64 构建英特尔线程构建块失败
- javascript - 使用 JavaScript 检查时将复选框/单选标签设为粗体
- javascript - 我想在文本冒险中实现一个健康栏
- angular - Angular 12 将 json 导入 ts