Read Single Char

Claudio Bley bley@wh2-19.st.uni-magdeburg.de
Tue Jun 10 23:52:00 GMT 2003


On Fri, Jun 06, 2003 at 01:59:15PM +0530, Bharathi S wrote:
> On Thu, 5 Jun 2003, John Love-Jensen wrote:
> 
> Thanks John,
> 
> > Probably because you are doing something like this on the input
> > stream: 1\n2\n3\n4\n5\n      Change your scanf to this:
> >     scanf("%c\n", &c);
> 
> 1st time, this go next stat only after reading 4 char ( 1\n2\n ). But 
> the outputs are correct. I am getting the output 1 after entering 2.

Hi.

The scanf man page says:

,----
| White space (such as blanks, tabs, or newlines) in the format string
| match any amount of white space, including none, in the input.
`----

So, if you specify a newline character in the format string of scanf
scanf will eat all newline characters as long as they keep coming.

What happens is that scanf can't return until you type some other
character than a newline. Since ttys are usually line buffered you
need to terminate every input with a newline -- hence the second
newline you needed to type until printf was called.

At the next iteration of the for loop scanf will be called again and
will instantly find the character(s) you typed after the last newline
but it must wait until there is some character other than a newline
and so on.

For instance, if you type "123\n" the program will immediately print:

 Input[0] ==> 49
 Input[1] ==> 50

because it is also valid if there is no newline between the
characters. 

In the end all depends on your needs. How do you want to define
"valid" input? It might be better to read a single line at first and
parsing that string instead of dealing with a stream of
characters. (you might also have a look at getchar and fgets)

HTH
-- 
Claudio Bley                                 ASCII ribbon campaign (")
Debian GNU/Linux user                         - against HTML email  X 
http://www.cs.uni-magdeburg.de/~bley/                     & vCards / \



More information about the Gcc-help mailing list