io_x
2/12/2011 2:09:00 PM
"John" <> ha scritto nel messaggio
> The program is supposed to read lines from the standard input, then each line
> is printed on the standard output preceded by its line number. The program
> should have no built-on limit on how long a line it can handle.
>
> So I wrote the following program in C, but I'm not sure that it is doing what
> it is supposed to do. I verified the source code against the solution in the
> back of the book and I'm pasting here what the solution in the back of the
> book is.
>
> #include<stdio.h>
> #include<stdlib.h>
>
> int main(){
>
> int ch;
> int at_beginning = 1;
> int line = 0;
>
> while( (ch==getchar())!= EOF){
>
> if(at_beginning == 1){
>
> at_beginning = 0;
> line+=1;
> printf("%d ", line);
>
> }
>
> putchar(ch);
>
> if(ch == '\n')
> at_beginning = 1;
> }
> return EXIT_SUCCESS;
> }
for me the above could
print at end one char not '\n' in stdout
but last char in a stdout, should be "\n".
this is my little try
the criticize i say, afther above 3 lines
is there is no need of "at_beginning"
(the first line is special)
as i show below
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define u32 unsigned
int main(void)
{int c;
u32 line=1, led=0;
while((c=getchar())!= EOF)
{if(led==0)
{led=1; /* the first line is special */
printf("%3u: ", line);
}
if(c=='\n')
{++line;
if((log10(line)+1.0)<=3)
printf("\n%3u: ", line);
else printf("\n%u: ", line);
}
else putchar(c);
}
if(c==EOF && led==0)
printf("File Vuoto\n");
else printf("\n"); /* the last char is \n */
return 0;
}