I want to make scanf only accept one character, but I am not familiar with the method of doing so. can anyone help me here.
here is my current code:
void push(S *stack){
char e;
S temp;
temp=malloc(sizeof(struct stack));
if(!temp){
printf("Failed\n");
return;
}
printf("Input value: \n");
scanf(" %c", &e);
if(('a'<=e && e<= 'z') || ('A'<=e && e<= 'Z')){
temp->data=e;
if(*stack == NULL){
temp->next = temp->prev = NULL;
*stack=temp;
} else {
temp->next = *stack;
(*stack)->prev = temp;
temp->prev = NULL;
*stack=temp;
}
printf("Success %c", e);
}else{
printf("Failed %c", e);
}
}
Forgot to mention:
if i were to input "abc" it will be pushed in the stack as a,b and c. though it is correct i was hoping to have a way to nullify the input and only accept it if its only a single character, if this is possible of course? if not then i will stick with the current one, was just hoping for a better implementation. thank you
Try this:
int ch;
...
printf("Input value: \n");
scanf(" %c", &e);
while( (ch = getchar()) != '\n' && ch != EOF); // To eat up all the characters left behind by scanf call including '\n'.
scanf
reads the first character you typed in to e
. The rest of the characters left behind in the buffer is read one by one to ch
by the getchar
in while
loop until it reads \n
. When it reads \n
then condition becomes false
and the loop is terminate. Now your buffer is empty.