gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:52:03 25 4
gpt4 key购买 nike

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

练习 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com