我正在练习C编程手册中的算法,并希望在输入每一行后输出其长度。我写完一个句子后,它给我正确的输出结果“这是长度为10的行”之类的东西。然后,不断重复“这是长度为1的线”,直到我控制+ z。如何获取它只是打印长度,然后每次都继续接收输入?
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line size */
int getlines(char line[], int maxline);
void copy(char to[], char from[]);
/* print longest input line */
int main()
{
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /*longest line saved here */
max = 0;
while ((len = getlines(line, MAXLINE)) > 0)
printf("This is the line length %d.", len);
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) /* there was a line */
printf("%s", longest);
return 0;
}
/* getline: read a line into s, return length */
int getlines(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;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
i++;
}
谢谢。
您忘记了将while循环的语句括在花括号中,并且您需要更改循环的条件。
while ((len = getlines(line, MAXLINE)) > 1 )
{
printf("This is the line length %d.", len);
if (len > max) {
max = len;
copy(longest, line);
}
}
或者while循环中的条件看起来像
while ((len = getlines(line, MAXLINE)) != 0 && line[0] != '\n' )
请注意,函数副本的第二个参数应具有限定符const
void copy(char to[], const char from[]);
我运行了它,还可以。但是,您需要注意,您使用的是max这个关键字,因此您的代码将无法正常工作。有关[max]的更多信息,请参见here
我做了一些修改以帮助您更好地查看:
int main() { int len; /* current line length */ int maxVal; /* maximum length seen so far */ char line[MAXLINE]; /* current input line */ //char longest[MAXLINE]; /*longest line saved here */ maxVal = 0; printf("Enter Input: "); while ((len = getlines(line, MAXLINE)) > 0){ printf("This is the line length %d.\n", len); if (len > maxVal) { maxVal = len; //copy(longest, line); printf("Longest Line is now: %s", line); } printf("Enter Input: "); } return 0; }
如果不需要longestLine,因为您只需要根据您的代码进行打印,就可以使用它。>
测试后的输出如下:
输入输入:您好
这是行长6。
最长的行现在是:您好
输入输入:世界
这是行长6。
输入输入:属世事务
这是行长16。
最长的线路现在是:世俗事务
输入输入:Hello World
这是行长12。
输入输入: