0

unable to understand why ?

#include <stdio.h>

int main()
{
      int i;
      printf("\n\nEnter 1st value : ");
      i=getchar();
      printf("\nvalue you've entered is \'%c\'\n\n", i);
      printf("Enter 2nd value : ");
      i=getchar();
      printf("\nvalue you've entered is \'%c\'\n", i);
      return 0;
}

the above code will not let me enter by 2nd value. It terminates to the very end 'Hit ENTER to continue'

I put a blank getchar() just above the second value line ... and viola the code suddenly worked ... it sought inputs for both values

i am puzzled ...

if not for, accidentally introducing the blank getchar() i was lost trying to figure out what was wrong in the above code ...

this code works, but no idea why the empty getchar() line was required ???

#include <stdio.h>

int main()
{
      int i;
      printf("\n\nEnter 1st value : ");
      i=getchar();
      printf("\nvalue you've entered is \'%c\'\n\n", i);
      getchar();    // why is it necessary to add this line ???
      printf("Enter 2nd value : ");
      i=getchar();
      printf("\nvalue you've entered is \'%c\'\n", i);
      return 0;

}
AIAMUZZ
  • 1
  • 3
  • 2
    What do you enter for the first input? A letter and additionally a return/newline? – Yunnosch Dec 08 '17 at 06:39
  • 1
    Don't use `getchar()` for interactive input. Use `fgets()`. – Greg Hewgill Dec 08 '17 at 06:39
  • 2
    The `Enter` key you press to give the first input is *also* stored in the input buffer, and is read by the second `getchar` call as a newline. That should be easily seen by reading the ***full*** output of your program. Or by [learning to *debug* your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Some programmer dude Dec 08 '17 at 06:40
  • 1
    @Greg Would you like to elaborate to give more insight into the reasons for that rule? – Yunnosch Dec 08 '17 at 06:40
  • On an unrelated note, you don't need to escape single-quotes `'` in double-quoted strings. A string such as `"Hello quote ' works"` is valid. – Some programmer dude Dec 08 '17 at 06:43
  • thanks for the learnings people ... currently i am just trying to understand/learn things as i am looking back into code after more than 15 years ... – AIAMUZZ Dec 09 '17 at 05:14
  • I think i figured out ... I had forgotten that enter is also treated as a character. Its a case of 'Uninvited Guest' and the accidental blank getchar() i introduced as a debug tool turns out was flushing it out ... 'Enter' the uninvited guest ... making way for my invited guest (2nd Value) !!! so effectively as a rule we need to add blank getchar() line if one is about to read inputs using getchar() down the line !!! thanks people – AIAMUZZ Dec 09 '17 at 05:26

0 Answers0