I am using c to create a very basic programme. I using scanf to get input from the console but when I use it with a char it just seems to 'skip' it.
Here is the code:
#include <stdio.h>
#include <string.h>
int main(){
char name[20];
char yn;
printf("Welcome to Benjamin's first C programme! \n\n");
do{
printf("What is your name? \t");
scanf("%s", name);
printf("\n");
printf("Is your name %s [y/n]?", name);
scanf("%c", &yn);
printf("\n");
} while(yn != 'y');
}
Add space at the begining of the string format in the second scanf()
scanf(" %c", &yn);
This space will catch the newline that you type after the first input
Your apparent skipping is because %s specifier matches a string of characters, until a whitespace or a newline character. In this case, it is a newline. The problem is that it leaves it in the input stream, and the next reading matches it. So, in your yn variable, there will always be the newline character. In order to prevent this, insert a space before %c specifier, to skill all blanks (whitespace, newline, tab):
scanf(" %c", &yn);
Also note that for the same reason, your program will not work if I insert my full name (i.e. I insert spaces).
As an alternative, try using getchar()
Replace:
scanf("%c", &yn);
With:
getchar();//eat the '\n' from <return>
yn = getchar();
For the record I like the other answers better, just offering this as an alternative...