-1

I am writing a simple code which takes a character from the user and prints it, if the character is q, then the loop breaks. but the output I am getting prints the print statement twice and second time its printing nothing please have a look at the image. Why is it printing twice?

#include<stdio.h>
void main()
{
  char c;
  printf("Enter a character: ");
  c=getchar();
  while(c!='q')
  {
     putchar(c);
     printf("\nEnter a character: ");
     c=getchar();
  } 
}
Manikumar Perla
  • 341
  • 4
  • 10

2 Answers2

3

You are pressing the Return/Enter key as part of the input. It remains in the input stream and immediately picked up by getchar in the next iteration.

If formatted input is an option, you can use scanf to skip whitespace characters when awaiting a character input:

scanf(" %c", &c); // Note the leading white-space, it's what does the skipping

If you do continue to use getchar, pay attention to its return type, which is int. It returns EOF when the input stream is exhausted, and that value is not a valid character, but an integer.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Thank you! that worked. I have a question. Shouldn't the getchar() function take one character per iteration? Why is it taking return as an input in the second iteration? – Manikumar Perla Feb 12 '17 at 13:26
  • @ManikumarPerla - Because the input stream is buffered. The keystrokes from the hardware are stored into a special array that your program reads from every time you call `getchar`. It's designed that way to make sure no input is lost. – StoryTeller - Unslander Monica Feb 12 '17 at 13:28
  • More to the point, the return character _is_ a character; when you type `x` and return, you are entering two characters. The `getchar()` function reads all characters — not just printing characters. – Jonathan Leffler Feb 12 '17 at 14:32
  • Thanks ! @JonathanLeffler – Manikumar Perla Feb 12 '17 at 17:03
2

What is buffer?
Temporary storage area is called buffer. All standard input and output devices contain input and output buffer. In standard C/C++, streams are buffered, for example in case of standard input,when we press the key on keyboard,it isn’t send to your program, rather it is buffered by operating system till the time is allotted to the program.

Typing “while ((getchar()) != ‘\n’);” reads the buffer characters till the end and discards them(including newline) and using it clears the input buffer and allows the input in the desired container.

The following code would work just fine :

#include<stdlib.h>
void main()
{
    char c;
    printf("Enter a character: ");
    c = getchar();
    while(c != 'q')
    {
        putchar(c);
        // flushes the standard input (clears the input buffer)
        while ((getchar()) != '\n');
        printf("\nEnter a character:");
        c = getchar();
    }

}
Ankit Joshi
  • 261
  • 2
  • 11