1
所以我试图确定一个学校任务的最长行。这是我认为有问题的代码。我不明白为什么“longest_line”在while循环中打印效果不错,但不会在循环外部打印。while循环Char阵列通过引用
int main() {
int ch;
char line[MAXLINE] = { '\n' }; /* current input line */
char longest_line[MAXLINE] = { '\n' }; /* copy of longest line */
while ((ch = readline(line, MAXLINE)) != EOF) {
if (longest(line, longest_line))
copy(longest_line, line);
printf("Read Line: %s\n", line);
printf("Long Line: %s\n", longest_line);
}
printf("Print Long Line: %s\n", longest_line);
这里是输出:
calc L
copy
Read Line: sdafasdfsadfsadfs
Long Line: sdafasdfsadfsadfs
calc L
Read Line: sadfs
Long Line: sdafasdfsadfsadfs
calc L
Read Line: sdfasdfsafd
Long Line: sdafasdfsadfsadfs
calc L
Read Line: sadfsdf
Long Line: sdafasdfsadfsadfs
calc L
Read Line: sadfs
Long Line: sdafasdfsadfsadfs
calc L
Read Line:
Long Line: sdafasdfsadfsadfs
calc L
Read Line: sfsafsdfsf
Long Line: sdafasdfsadfsadfs
Print Long Line:
这就像longest_line获取循环,这没有任何意义我后删除。对不起,我是一个新手。感谢那个知道这个异常背后的技术原因的人。
这里是我的整个程序,如果你想运行它(我固定变量)
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#define MAXLINE 80 /* maximum input line size */
/* function declarations */
int readline(char line[], int max);
void copy(char to[], char from[]);
bool longest(char read_line[], char previous_line[]);
/* print longest input line */
int main() {
int ch;
char line[MAXLINE] = { '\n' }; /* current input line */
char longest_line[MAXLINE] = { '\n' }; /* copy of longest line */
while ((ch = readline(line, MAXLINE)) != EOF) {
if (longest(line, longest_line))
copy(longest_line, line);
printf("Read Line: %s\n", line);
printf("Long Line: %s\n", longest_line);
}
printf("Print Long Line: %s\n", longest_line);
return 0;
}
/* readline: read a line into s, return length */
int readline(char s[], int lim) {
int i = 0; // the current index
char c; // the current char
c = getchar();
while (c != '\n' && i < lim) {
s[i] = c;
i++;
c = getchar();
}
s[i] = '\0'; // final charachter of string
return c;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[]) {
int i;
for (i = 0; to[i] = from[i]; ++i);
printf("copy\n");
}
/* longest: Which line is the longest */
bool longest(char read_line[], char previous_line[]) {
printf("calc L\n");
char ch;
int size_read = 0;
int size_previous = 0;
// determine length of read line
ch = read_line[size_read];
while (ch != '\0') {
ch = read_line[size_read];
++size_read;
}
// determine length of previous line
ch = previous_line[size_previous];
while (ch != '\0') {
ch = previous_line[size_previous];
++size_previous;
}
// determine longest line
if (size_read > size_previous)
return true;
else
return false;
}
适用于我的系统 - 除了longest_line最初未初始化的事实。 – fpw
由于某些原因,你不能使用函数'strcpy'和'strlen'?这将摆脱“复制”功能和“最长”的大部分 – MondKin
是的,我们必须编写出自己的任务 – user3043594