字符数组c&k;r第1-17册
我正在通过K&R工作,我试图编写一个程序,打印出所有大于80个字符的输入行。一旦我在终端上运行程序,我什么也得不到。谁能告诉我哪里出了问题?我不确定的另一部分是行字符数组c&k;r第1-17册,c,arrays,kernighan-and-ritchie,C,Arrays,Kernighan And Ritchie,我正在通过K&R工作,我试图编写一个程序,打印出所有大于80个字符的输入行。一旦我在终端上运行程序,我什么也得不到。谁能告诉我哪里出了问题?我不确定的另一部分是行s[I]='\0'-有人能给我解释一下这是怎么回事吗 #include <stdio.h> #define MAXLINE 1000 #define LENGTH 80 int get_line(char line[], int maxline); /* program to print all lines longer
s[I]='\0'代码>-有人能给我解释一下这是怎么回事吗
#include <stdio.h>
#define MAXLINE 1000
#define LENGTH 80
int get_line(char line[], int maxline);
/* program to print all lines longer than 80 characters */
main()
{
int len; /*current line length*/
char line[MAXLINE]; /*current input line*/
while((len = get_line(line, MAXLINE)) > 0) /*while length of the line is greater than zero*/
if (len > LENGTH) { /*if the length is greater than 80*/
printf("%s", line); /*print that line*/
return 0;
}
}
/* getline: read a line into s, return length */
int get_line(char s[], int lim)
{
int c, i;
for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) /*if i is < 1000 & input is = EOF & input is != newline add one*/
s[i] = c; /*assign a value to each character*/
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0'; /*unsure what '\0' does*/
return i; /*return the length*/
}
#包括
#定义MAXLINE 1000
#定义长度80
int get_行(字符行[],int maxline);
/*用于打印超过80个字符的所有行的程序*/
main()
{
int len;/*当前线路长度*/
字符行[最大行];/*当前输入行*/
而((len=get_line(line,MAXLINE))>0)/*而线的长度大于零*/
如果(len>LENGTH){/*如果长度大于80*/
printf(“%s”,行);/*打印该行*/
返回0;
}
}
/*getline:将一行读入s,返回长度*/
int get_行(字符s[],int lim)
{
int c,i;
对于(i=0;i
s[i] = '\0';
将nul终止符追加到字符串。这是表示字符串结尾的C-ism
至于你的问题,这个程序对我来说很好
$ cat line80.c | ./line80
while((len = get_line(line, MAXLINE)) > 0) /*while length of the line is greater than zero*/
$ ./line80 < line80.c
while((len = get_line(line, MAXLINE)) > 0) /*while length of the line is greater than zero*/
$cat line80.c |/line80
而((len=get_line(line,MAXLINE))>0)/*而线的长度大于零*/
$./line800)/*而线的长度大于零*/
我看到您的代码的唯一问题是,它在打印第一行超过80个字符后立即停止
如果你移动
return 0;
在if语句之外,它将打印超过80个字符的所有行,而不仅仅是第一行
你的“主要”方法就是
main()
{
int len; /*current line length*/
char line[MAXLINE]; /*current input line*/
while((len = get_line(line, MAXLINE)) > 0) /*while length of the line is greater than zero*/
if (len > LENGTH) /*if the length is greater than 80*/
printf("%s", line); /*print that line*/
return 0;
}
正如其他人指出的那样,“\0”字符是C字符串终止符。它看起来正确。我认为您没有正确运行它。您是如何运行它的?它只会打印大于80的第一行,而不是所有大于80的行。cat main.C |/a.out
-适用于me@pb2qop发布的内容(/line80
)很好。从main返回0,程序将以成功状态结束。谢谢,感谢您的帮助