0

I have this following code.

#include <stdio.h>
int main () {
    char letter1;
    char letter2;

    printf("Enter Letter 1: ");
    letter1 = getchar();
    printf("\n");

    printf("Enter Letter 2: ");
    letter2 = getchar();
    printf("\n");

    printf("%c - %c\n", letter1, letter2);
    return(0);
}

I am trying to use getchar() to define letter1 and letter2, however it will only work for letter1, then set the value of letter2 to '\n'. Does anyone know a work around for this, so I can type values for both variables?

J...S
  • 5,079
  • 1
  • 20
  • 35
User9123
  • 675
  • 1
  • 8
  • 20
  • 1
    You are typing letter1 then the return key and the code shows letter1 and then the newline which represents the return key? In that case the program does exactly what you told it to do. Did you consider ignoring anything but an accepted letter? I.e. just ignore the newline and use another getch() to look for the desired second non-whitespace. – Yunnosch Jul 29 '18 at 05:12
  • @Yunnosch You did mean `getchar()` and not `getch()`, right? – Spikatrix Jul 29 '18 at 05:38
  • Not the problem but `letter1` and `letter2` should be of type `int` as `getchar` returns an `int` – Spikatrix Jul 29 '18 at 05:39
  • @CoolGuy Sure, lazy typing and lack of double checking ... Thanks for catching. – Yunnosch Jul 29 '18 at 05:49

1 Answers1

1

This is because when you press the first letter and type the Enter key, you send the codes for the letter and the '\n' one after the other to the input buffer from where it will be consumed.

So the first getchar() get the code for the letter you typed and thus the letter is removed from the input buffer but that of \n remains which is consumed by the next getchar().

Inorder to avoid this, you need to keep consuming from the input buffer till the '\n' is consumed.

One way of doing this is

int c;
while( (c=getchar())=='\n' && c!=EOF);

This will keep on consuming from the input buffer as long as the read character is a \n and EOF is not reached. getchar() would return EOF on error.

int letter1, letter2;
int c;
printf("Enter Letter 1: ");
letter1 = getchar();
printf("\n");
printf("Enter Letter 2: ");
while( (c=getchar())=='\n' && c!=EOF);
letter2=c;
printf("\n");
printf("%c - %c\n", letter1, letter2);

Edit: As pointed out in the comments, note that getchar() returns an int and not a char. See this post.

J...S
  • 5,079
  • 1
  • 20
  • 35