Find the answer to your Linux question:
Results 1 to 4 of 4
Hello, I am trying to use getch() from ncurses to escape from a looping, but it doesn´t work. _____________________________________________ void flush_in(){ int ch; while ((ch=fgetc(stdin)) != EOF && ch != ...
  1. #1
    Just Joined!
    Join Date
    Nov 2007
    Posts
    1

    getch() doesn´t work!

    Hello,

    I am trying to use getch() from ncurses to escape from a looping, but it doesn´t work.

    _____________________________________________
    void flush_in(){
    int ch;
    while ((ch=fgetc(stdin)) != EOF && ch != ´/n´)
    {}
    }

    void main()

    .....
    printf("Direção de rotação: (H)orário (A)nti-horário");
    scanf("%c", &direcao);
    flush_in();
    printf("Velocidade: 1 - 2 -3 - 4");
    scanf("%d", &vel);
    flush_in();

    printf ("Parar o motor: pressione p");

    while (getch() != ´p´)
    {}
    }

    Has anybody any idea what is happening?

    Thanks in advance!

  2. #2
    Just Joined!
    Join Date
    Nov 2007
    Location
    Camp Pendleton
    Posts
    55
    Hi,

    Unless the rest of your program is curses, you need to stick to stdio functions. Try getchar().

    man 3 getchar

  3. #3
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    getchar() is good for getting a single character, but it still leaves your keyboard in "line mode" if it was there before; your program won't see the "p" until you've pressed the <Enter> or <Return> key.

    The way out of this is to use tcsetattr(). I hope this is enough to help you. I'm on the road, and can't give more help right now. Perhaps someone else who knows about tcsetattr() can jump in and help. If not, I'll be back from traveling on Wednesday and give you more detailed help than you possibly could want.
    --
    Bill

    Old age and treachery will overcome youth and skill.

  4. #4
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    If you decide to use tcsetattr(), it's probably best to stick with reading one character at a time, and doing something special when you see a carriage return ('\r'), like turning it into a line feed ('\n'), placing it at the end of the line buffer, putting a NUL character after that, and processing the line. And you may as well read that character using the read() function.

    Here are some sample programs which demonstrate how to do this in character mode rather than line mode. I had to make their extensions .txt instead of .c because of the limitations of this site's uploading machinery, but you know what to do.

    Hope this helps.
    Attached Files Attached Files
    --
    Bill

    Old age and treachery will overcome youth and skill.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...