该程序假设打印出所有输出中最长的一行。但该程序表现得非常奇怪。有时它甚至在EOF(ctrl + Z)被触发时也不会终止,有时会打印出空白或奇怪的符号。我不知道为什么它不起作用;有人可以帮我解决吗?
//START
#include <stdio.h>
#include <stdlib.h>
#define mx 100
int main(void)
{
int line[mx],lng[mx],c,word,maxim;
word=1;
maxim=10;
int i=0;
while((c=getchar())!=EOF)
{
while((c=getchar())!='\n')
{
line[i]=(c=getchar());
if(((c=getchar())==' ') || ((c=getchar())=='\t'))
{
word++;
}
i++;
}
if(woasdrd>=maxim)
{
for(int d=0;d<=99;d++)
{
copyline(lng[d],line[d]);
}
word=1;
i=0;
}
else
{
i=0;
word=1;
}
}
for(int g;g<=99;g++)
{
putchar(lng[g]);
}
}
copyline(int to[],int from[])
{
for(int i=0;i<=99;i++)
{
to[i]=from[i];
}
}
//END
#include <stdio.h>
#include <stdlib.h>
#define mx 100
//copy string array from from[] to to[],and both of it is end with '\0'
void copyline(char to[],char from[])
{
int i = 0;
while( from[i] )
{
to[i]=from[i];
i++;
}
}
int main(void)
{
char line[mx] = { ' ' },lng[mx] = { ' ' }; //line keep the line you just input,lng keep the longest line
int maxim , c; //maxim keep the longest num of longest line
int i=0;
maxim=0;
//get input from stdin ,if EOF then end(Ctrl + C or Ctrl + d is EOF)
while( ( c = getchar() ) != EOF )
{
//if you input a Enter then compare it's length with maxim
if( c == '\n' )
{
line[i++] = '\0'; //turn '\n' into '\0',for string end with '\0'
if( i > maxim ) //compare the line you just input with the longest line,if get longer one,copy it to lng
{
maxim = i;
copyline( lng , line );
lng[ i ] = '\0'; //for string end with '\0'
}
i = 0; //if you get a '\n' ,then you should be ready for next input line,so i = 0,and continue for new get
continue;
}
line[i++] = c; //keep input to line
}
//that's output,for string end with '\0',so put it as condition for while loop
i = 0;
while( lng[i] )
{
printf("%c",lng[i++]);
}
printf("\n");
}
也许这就是你想要的,起初我想改进你的代码,但它有很多错误,包括逻辑和代码,所以我重写你的代码。如果你有这个代码的问题,请告诉我。
我想你在太多地方打电话给getchar()
。每次调用时都会从输入中删除一个字符。真的,你应该在第一个while循环之前调用c=getchar()
一次来读取第一个字符。删除其余的c=getchar()
,然后使用c
。然后在i++;
之后的内部while循环结束时,你应该使用c=getchar()
来读取下一个字符。