gpt4 book ai didi

C 中无法打印最大行

转载 作者:行者123 更新时间:2023-11-30 15:40:32 25 4
gpt4 key购买 nike

该程序应该打印出所有输出中最长的行。但是该程序的行为非常奇怪。有时,即使触发 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");
}

也许这就是你想要的,一开始我想改进你的代码,但是它有很多错误,包括逻辑和代码,所以我重写了你的代码。如果你对此代码有问题,请告诉我。

关于C 中无法打印最大行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20963311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com