当我初始化我的数组“temp”和“string”时,我希望它们能够保存长度为1000的字符串,因为我用MAXLEN初始化它们,它保持值1000.但是,当我输入一个大于第一个的字符串时我输入的一个我收到的消息:
命令终止
我相信错误在复制功能中,但我不明白它在哪里或为什么发生。
#include <stdio.h>
#define MAXLEN 1000
int longestLine(char s[]);
void copy(char to[], char from[]);
// prints the longest line, and length of the longest line
int main()
{
int max;
char string[MAXLEN];
max = longestLine(string);
printf("max length is %d\n", max);
printf("%s\n", string);
return 0;
}
// returns the longest line in an input
int longestLine(char s[])
{
int max, cnt, c;
char temp[MAXLEN];
max = cnt = 0;
while((c = getchar()) != EOF)
{
if (c == '\n')
{
if (cnt > max)
{
max = cnt;
copy(s, temp);
}
cnt = -1; //if newline reset count
}
temp[cnt] = c;
cnt++;
}
return max;
}
// copys array contents from "from" to "to"
void copy(char to[], char from[])
{
int i;
for (i = 0; from[i] != '\0'; ++i)
{
to[i] = from[i];
} }
随着输入:
this is line one
this is line two which is longer
这是预期的输出:
max length is 32
this is line two which is longer
这是实际输出:
Command terminated
感谢您的帮助!
编辑:
弄清楚,行cnt = -1让我搞砸了。谢谢!
两件事情: