0

When we execute the following code:

#include <stdio.h>

int main(void){
    char x,y;
    scanf("%c", &y);
    x = getchar();
    putchar(x);
    return 0;
}

The enter that is being inputted in the scanf("%c", &y); statement is passed on to x. Is there some way to get away with this? I now that if we are using scanf then we can ignore the \n by scanf("%*c%c", &x); but don't know what do while using getchar().

  • Clear the input buffer – Ardent Coder May 24 '20 at 12:10
  • please clarify what do you mean by that –  May 24 '20 at 12:13
  • 1
    It the goal is to read a _line_ of user input, start with `fgets()` and a generous sized buffer, Then parse the buffer for `char y`. – chux - Reinstate Monica May 24 '20 at 12:15
  • I'm not sure if that's the best way, but it will work in your case: https://stackoverflow.com/questions/7898215/how-to-clear-input-buffer-in-c. Do it before calling `getchar`. – Ardent Coder May 24 '20 at 12:15
  • @Someprogrammerdude OP wants to do the same thing using `getchar`. – Ardent Coder May 24 '20 at 12:18
  • 1
    First of all you need to remember (or learn) that [`getchar`](https://en.cppreference.com/w/c/io/getchar) returns an **`int`**. This is important for any `EOF` check that you really need to have. The second thing to solve your problem is to read character by character in a loop until you have read the newline (or hit end-of-file). – Some programmer dude May 24 '20 at 12:19

2 Answers2

0

It's basically the problem of the input buffer, In your case, you can use alternative input-string getchar() with fflush(stdin); for handling this issue.

Amandeep
  • 41
  • 6
  • 1
    The second `scanf` doesn't need the `getchar` call, all you need is to tell `scanf` to skip leading white-space by adding a single space in the format string: `scanf(" %c", &b);` – Some programmer dude May 24 '20 at 12:20
  • `fflush(stdin)` is UB. – Ardent Coder May 24 '20 at 12:22
  • @Amandeep The C specification explicitly say that passing an input-only stream (like `stdin`) to `fflush` is UB. One common compiler unfortunately adds it as a non-portable extension of the language. Such extensions should be avoided (at all cost IMO). – Some programmer dude May 24 '20 at 12:29
0

You can do something like this

#include <stdio.h>

int main(void)
{
    char x,y,ch;

    scanf("%c%*c", &y);
    while((ch=getchar())!='\n'&&ch!=EOF); //removes all character in input buffer
    x = getchar();
    putchar(x);
    return 0;
}
srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25