[英]Can't print in largest line in C
該程序假定在所有輸出中打印出最長的一行,但是該程序的行為很奇怪。 有時即使觸發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循環的結尾處i++;
您應該使用c=getchar()
讀取下一個字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.