c - K&R 第一版,练习 1.18(for 语句中的测试很笨拙)

标签 c loops for-loop while-loop

对于“循环语句中的测试”在编程方面的含义,我无法得出任何结论。是关于循环括号中的测试还是由循环迭代的大括号中的测试?

练习 1.18 在这里:

char line[];
int max; 

main() 
{
    int len;
    extern int max;
    extern char save[];

    max = 0;
    while((len = getline(line, MAXLINE)))
    if (len > max){
        max = len;
        copy();
    }
    if (max > 0)  printf("%s",save);
}

getline() 
{
    int c,i;
    extern char line[];

    for (i=0; i<= MAXLİNE -1 && ((c = getchar())!= EOF) && c != '\n';) 
        line[i++]=c;
    if (c == '\n')
    {
        line[i] = c; 
        ++i;
    } 
    s[i] = '\0';
    return (i) ;
}

copy()   
{                          
    int i;
    extern char save[];
    extern char line[];

    int i = 0;
    while( (save[i] = line[i] ) != '\0') 
        ++i;
}

Exercise l-18. The test in the for statement of getline above is rather ungainly. Rewrite the program to make it clearer, but retain the same behavior at end of file or buffer overflow. Is this behavior the most reasonable?

最佳答案

从注释中可以看出,似乎应该重写 for 循环以使代码更具可读性。

我可以建议以下解决方案,用 for 循环代替 while 循环。

getline() 
{
    int c, i;
    extern char line[];

    i = 0;

    while ( i <= MAXLINE -1 && ((c = getchar()) != EOF) && c != '\n' )
    { 
        line[i++] = c;
    }

    if (c == '\n')
    {
        line[i++] = c; 
    } 

    line[i] = '\0';

    return i;
}

重写函数后我发现了一个错误。变量 c 必须初始化,并且 while 循环中的第一个子条件也必须更改。

所以该函数可以看起来像

getline() 
{
    int c, i;
    extern char line[];

    i = 0;
    c = EOF;

    while ( i < MAXLINE - 1 && ((c = getchar()) != EOF) && c != '\n' )
    { 
        line[i++] = c;
    }

    if (c == '\n')
    {
        line[i++] = c; 
    } 

    line[i] = '\0';

    return i;
}

这是一个演示程序

#include <stdio.h>
#include <string.h>

#define MAXLINE 10

char line[MAXLINE];

int getline( void )
{
    int c, i;
    extern char line[];

    i = 0;
    c = EOF;

    while (i < MAXLINE - 1 && ((c = getchar()) != EOF) && c != '\n')
    {
        line[i++] = c;
    }

    if (c == '\n')
    {
        line[i++] = c;
    }

    line[i] = '\0';

    return i;
}

int main( void )
{
    int max = 0;
    int len;
    char save[MAXLINE];

    while ((len = getline()))
        if (len > max) {
            max = len;
            strcpy( save, line );
        }
    if (max > 0)  printf("%s", save);

    return 0;
}

它的输出(如果在 Windows 中作为控制台应用程序运行)可能如下所示

1
123456789
12345
123
1234567
^Z
123456789

关于c - K&R 第一版,练习 1.18(for 语句中的测试很笨拙),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47800902/

相关文章:

vba - 更改 map 颜色的宏(州)

javascript - Nightmare Promises with for..loop api calls, waterfall & anti-pattern (Bluebird.js)

JavaScript For Loop double 值 365 次

谁能解释这个递归函数我不明白它如何返回任何东西?

struct中的char初始化

javascript - 在 Javascript 循环中以编程方式为 imgs 设置唯一的 onclicks

vba - Excel VBA 中的循环单词匹配函数

c - 如果无符号类型不应该有负值,为什么当我打开所有位时它是负值?

c - 实现函数队列调度的2D队列

python - 为什么我不能在定义中使用循环 'for i in...'? (我没有使用局部变量)