'c program doesn't takes "space" as input to show the acsii code
The program shows output for all other characters instead of space. When I enter "space" it doesn't do anything and just waits.
#include<stdio.h>
#include<stdbool.h>
int main(){
char c;
while(true){
printf("Enter character:");
scanf("\n%c", &c);
if (c == 27 )break;
printf("ascii value:%d\n", c);
}
return 0;
}
The output for all other character comes fine.
Enter character:r
ascii value:114
Enter character:e
ascii value:101
Enter character:c
ascii value:99
Enter character:p
ascii value:112
Enter character:^[
I don't understand what's going on!
Solution 1:[1]
When I enter "space" it doesn't do anything and just waits.
scanf("\n%c", &c);
does not mean read a line-feed, then a character.
Instead "\n%c"
means to read any number of white-spaces like '\n'
, space, tab, .... and then read a character.
OP's code is stuck reading white-spaces.
Instead, read a line. Below has minimal testing and only pays attention to the first char
in a line of input.
// scanf("\n%c", &c);
char buf[80];
if (fgets(buf, sizeof buf, stdin) == NULL) {
fprintf(stderr, "Input is closed\n");
return -1;
}
c = buf[0];
Remember the Enter is a char
too.
To read the escape character, other input functions may be needed.
Solution 2:[2]
#include<stdio.h>
#include<stdlib.h>
void clear_buffer(){
char ch;
while(1){
ch = getchar();
if (ch == '\n' || ch == EOF ) break;
}
}
int main(){
char c;
while(1){
printf("Enter character:");
scanf("%c", &c);
if (c == 27 )break;
printf("ascii value:%d\n", c);
clear_buffer();
}
return 0;
}
The function clear_buffer
clears the buffer(enter character gets cleared) so that only the first character is accepted and none of the other characters after that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |