c - getchar() with non-canonical mode on UNIX and Windows -


i want record user's input, printing * until enter key pressed. purpose, disable echo , canonical mode keyboard, , use code this:

while ((aux = getchar()) != '\n') {     buffer[i++] = aux;     printf("*"); } buffer[i] = 0; printf("\n"); 

this code works perfect on unix systems, not in windows. guess problem be, wrote pieces of code each platform:

unix

#include <stdio.h> #include <termios.h>  int main () {     int c;     struct termios mode;      tcgetattr(0, &mode);     mode.c_lflag &= ~(echo | icanon);     tcsetattr(0, tcsanow, &mode);      while (1)     {         c = getchar();         printf("%d\n", c);     }      return 0; } 

windows

#include <stdio.h> #include <windows.h>  int main () {     int c;     dword mode;     handle console = getstdhandle(std_input_handle);      getconsolemode(console, &mode);     setconsolemode(console, mode & ~(enable_echo_input | enable_line_input));      while (1)     {         c = getchar();         printf("%d\n", c);     }      return 0; } 

the result in unix that, each time press enter, number 10. that's perfect. result in windows is:

  1. first time press enter, printf("%d\n", c) substitutes %d nothing.
  2. second time press enter, printf("%d\n", c) substitutes %d 13.

i think problem may related fact new line characters represented in windows cr+lf, don't know how handle detect first time enter key pressed make first snippet of code work.

in windows can use getch() declared in conio.h instead of getchar() want.

example code:

 #include<conio.h>  #include<stdio.h>   int main()  {  int aux,i=0,buffer[max];  while ((aux = getch())!=13)  {   buffer[i++] = aux;   printf("*"); } return 0; } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -