+ 1
Why second scanf is not working
Why c only takes first scanf for character variable #include <stdio.h> int main() { char a,b; printf("enter a character\n"); scanf("%c",&a); printf("enter second character\n"); scanf("%c",&b); printf("%c%c",a,b); return 0; }
2 Answers
+ 4
While using getchar() works just fine it isn't needed. All you need to do is add a space before the second %c to consume the remaining whitespace character '\n' that is left in the input stream.
#include <stdio.h>
int main()
{
char a,b;
printf("enter a character\n");
scanf("%c",&a);
printf("enter second character\n");
scanf(" %c",&b); // space before %c consumes '\n'
printf("%c%c",a,b);
return 0;
}
+ 2
If you enter more than a character for the first scanf the second scanf will not work because it can only store 1 character. And when you enter a character and then press enter the first character is stored in the a variable and the enter pressed is stored in second variable.
So we can use the getchar() function to capture the enter pressed after the first scanf:
#include <stdio.h>
int main() {
char a,b;
printf("enter a character:");
scanf("%c",&a);
getchar();
printf("enter second character: ");
scanf("%c",&b);
printf("%c%c",a,b);
return 0;
}