[LCP]printf Question

sasidhar p psasidhar at hotmail.com
Fri Aug 31 08:39:13 UTC 2001


Thanx Andrew Weaver,
that cleared my doubt...


>From: Andrew Weaver <Andrew.Weaver at tecnomen.fi>
>Reply-To: linuxcprogramming at lists.linux.org.au
>To: "'linuxcprogramming at lists.linux.org.au'" 
><linuxcprogramming at lists.linux.org.au>
>Subject: RE: [LCP]printf Question
>Date: Thu, 30 Aug 2001 11:31:24 +0300
>
>In fact, it will print out one more hi than the number of chars you input.
>
>That is, it says Hi, you input AAAA, it will say Hi five times.
>
>Software does exactly what you tell it to do, not always what you meant
>but...
>
>What is happening is that getchar returns one char from the stream (stdin).
>When you type in a char, you also type in the carriage return don't you? 
>So,
>you have two chars in the stream (the char plus the newline). If you want 
>to
>see it, add the following line after the getchar() call...
>
>  printf("Input is:%c\n", getchar());
>
>Now, when your prog says "Hi", type in AAA + carriage return. You will see
>output like this...
>
>./a.out
>Hi
>AAA
>Input is:A
>Hi
>Input is:A
>Hi
>Input is:A
>Hi
>Input is:
>                            ***** Here is the Carriage Return
>Hi
>
> > -----Original Message-----
> > From:	sasidhar p [SMTP:psasidhar at hotmail.com]
> > Sent:	Thursday, August 30, 2001 10:01 AM
> > To:	linuxcprogramming at lists.linux.org.au
> > Subject:	[LCP]printf Question
> >
> > Hi,
> > Can somebody explain me this behaviour, I am all confused....
> > main()
> > {
> >    while(1)
> >    {
> >       printf("Hi\n");
> >       getchar();
> >    }
> > }
> >
> > Out put :
> >
> > [psasi at jldev 2]$ ./a.out
> > Hi
> > a
> > Hi
> > Hi
> > b
> > Hi
> > Hi
> > c
> > Hi
> > Hi
> > d
> > Hi
> > Hi
> >
> > [psasi at jldev 2]$
> >
> > I am using gcc on Linux 2.2.14
> > why is the "Hi" getting printed twice...
> >
> > I tried the following variants, but the o/p pattern is same...
> > #include <stdio.h>
> > #include <unistd.h>
> >
> > main()
> > {
> >    char buf[]="Hi\n";
> >    while (1)
> >    {
> >       write(1,buf,3);  /* I tried writing to fd 2 also*/
> >       getchar();
> >    }
> > }
> >
> >
> >
> > _________________________________________________________________
> > Get your FREE download of MSN Explorer at 
>http://explorer.msn.com/intl.asp
> >
> > _______________________________________________
> > This is the Linux C Programming List
> > :  http://lists.linux.org.au/listinfo/linuxcprogramming List
>_______________________________________________
>This is the Linux C Programming List
>:  http://lists.linux.org.au/listinfo/linuxcprogramming List


_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp




More information about the linuxCprogramming mailing list