EmbLogic's Blog

Query in Assignment 2 : Q14

In Q14, I’m reading the input through scanf. // scanf(“%c”,&arr[i]); in a while loop. The problem is it is taking two characters for a single character entered. I guess it is even taking ‘Enter’ / Carriage return as a input character. Someone suggested to use scanf(“\n%c”,&arr[i]);  and it worked. But I wasn’t able to understand the reason. Even fflush(stdout) was suggested. Can anyone explain me the reason precisely ?  Thanks in advance.

2 Responses to Query in Assignment 2 : Q14

  1. John Mcarthur says:

    scanf here reads 1 character, but the keyboard input has more than one character in it. If you enter “a” for a character input, you actually have two characters, the a followed by the \n.Scanf will leave the \n in the buffer for the next read so it’s up to you to read off the rest of the characters so you have a clean buffer for the next read.
    Try flush the buffer. This will clear any \n characters.

    scanf(“%c”, &arr[i]);
    flushall();

  2. i also thought this would be work

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>