0
#include <stdio.h>

void square(char x)
{
    printf("Enter x again: ");      //the code stops after printing this line**
    scanf("%c", &x);
    printf("%c", x);
}

int main(void)
{
    char x;
    printf("Enter x: ");
    scanf("%c", &x);
    square(x);
    return 0;
}

I want the code to take input in the square function, but it stops before that. I know if i use another variable instead of x in the function it will probably work but i want to reuse this variable.

mch
  • 9,424
  • 2
  • 28
  • 42
Elachi
  • 3
  • 1
  • 3
  • 3
    When you give the first input you terminated that with the `Enter` key, right? That `Enter` key press will be added to the `stdin` input buffer that `scanf` reads from, as a newline `'\n'`. That's what you read with the second input. To stop `scanf` from reading the newline, you need to tell it to skip all leading white-space, by adding an actual space in the format string. So change `"%c"` to `" %c"`. (There's at least one duplicate which I'm sure someone with more patience than me will dig up, which is why I didn't post an answer). – Some programmer dude Mar 25 '22 at 08:03
  • 1
    A decent text-book, tutorial or teacher should have mentioned this fact and the solution. And a minute stepping though the code in a debugger should also have made the problem quite obvious. – Some programmer dude Mar 25 '22 at 08:06
  • It worked! Can't believe i was so frustrated over something so simple, thanks! – Elachi Mar 25 '22 at 08:07
  • Always use `fgets()` for user input. Forget `scanf()` exists. – pmg Mar 25 '22 at 08:10

0 Answers0