Reputation: 311
I'm trying to write an example program in C which reads user input character by character, without the user having to press enter. I have used the code seen here, and it works just fine, with a slight issue. I want to process all of the user's input when they press enter, and when I use system(/bin/stty raw);
, the program can no longer detect it. As in:
int n, i;
char buffer[50];
system ("/bin/stty raw");
for(i=0; i<30 ; i++) {
buffer[i] = getchar();
printf("%d\n", buffer[i] == '\n'); //this prints 0 when I press enter
if(buffer[i] == '\n'){
break;
}
}
printf("%s\n",buffer);
system ("/bin/stty cooked");
Is there a way to detect the user pressing enter when doing this?
What I'm actually trying to do is read the user's input before they press enter, but do something when they do. Another way I thought of doing this is, if I were to not read it character by character, but rather using, for example fgets(buffer, 255, stdin);
, is there a way to read stdin 's buffer before the user pressing enter? I want to use the Enter key for this, so terminating the user input on another character, like with while((c=getchar())!= '.'){}
, used here is not an option.
Upvotes: 0
Views: 1629
Reputation: 123680
The terminal settings you disable with stty raw
are also responsible for harmonizing \r
and \n
.
You can use stty -icanon min 1
to only disable buffering, or alternatively accept both \r
and \n
as enter.
PS: It's considered good practice to use the TCGETS/TCSETS ioctls to get, modify and reapply the previous settings rather than invoking stty
and forcing cooked mode afterwards.
Upvotes: 3