Find the answer to your Linux question:
Results 1 to 2 of 2
Hi. I need a program that user enters characters but they shouldn't be visible on screen. So I wrote the following program. However getch() doesn't wait for a character to ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Feb 2010
    Posts
    1

    curses getch() help


    Hi. I need a program that user enters characters but they shouldn't be visible on screen. So I wrote the following program. However getch() doesn't wait for a character to be entered and returns -1. The program exits immediately. I tried cbreak(), raw(), noecho() but they didn't work. I couldn't understand their meanings also. Where can be the problem?

    #include <stdio.h>
    #include <curses.h>

    int main(void)
    {
    int x,y;

    printf("Enter two character\n");
    x = getch();
    y = getch();
    printf("Entered Values = %c and %c\n",x,y);
    printf("Entered Values = %d and %d\n",x,y);

    return 1;
    }

  2. #2
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    I have this old piece of code that might help. It grabs the text that's typed into a terminal and writes it to a file..

    Code:
    #include <iostream>
    #include <fstream>
    #include <termios.h>
    #include <stdio.h>
    #include <unistd.h>
    
    int main(int argc, char**argv)
    {
    	std::ofstream			fout("datafile");
    	if (fout.fail())
    	{
    		std::cout<<"could not open file!\n";
    		unlink("test");
    		return 1;
    	}
    	char ch;
    	struct termios original_t, new_t;
    	const int STDIN = 0;
    
    	tcgetattr (STDIN, &original_t);
    	new_t = original_t;
    	new_t.c_lflag &= ~(ICANON|ECHO);
    
    	std::cout<<"enter password->";
    	tcsetattr (STDIN, TCSAFLUSH, &new_t);
    	fflush(0);
    
    	while ((ch = std::cin.get()) != '\n')
    	{
    		fout<<ch;
    	}
    	fout<<ch;
    	fout.close();
    	unlink("test");
    	std::cout<<"\ngot password!\n";
    	tcsetattr (STDIN, TCSANOW, &original_t);
    	return 0;
    }
    Make mine Arch Linux

Posting Permissions

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