tags:

views:

1949

answers:

6

Hello Folks,

I've been Googling around with no luck. I'm looking for a way to do getc() or gets() or whatever that does not echo to the terminal. I saw kbhit() but this doesn't appear to be part of ANSI. Ideally, I'd like code that looks like

char s[100];
no_echo_gets(s); /* Won't echo to screen while being typed */
printf("%s\n", s);

Does anybody know a good ANSI compliant way to do this?

A: 

There isn't one; neither ANSI C nor ISO C++ have such a thing.

anon
+1  A: 

For UNIX-like systems you want to play with the ECHO flag...

#include <termios.h>
...
struct termios t;
tcgetattr(fd, &t);
t.c_lflag |= ~ECHO;
tcsetattr(fd, TCSANOW, &t);
...
dwc
Southern Hospitality
A: 

This will depend on your environment, it is not something that the language provides. If you intend to do extensive character mode I/O, you might look into a library like curses. Otherwise, you will have to manipulate the terminal or the windows console manually.

Sam Hoice
+4  A: 

You can't do it in a cross-platform manner using ANSI C. You'll have to use some OS-specific code, or use a library such as ncurses.

Adam Rosenfield
A: 

ANSI and ISO C do not define this functionality, however most C compilers have getch() or a close variation.

You'll need to do a preprocessor define for each compiler you're using that has a different library and function for this. It's not difficult, though you might consider it annoying.

Adam Davis
Does getch() prevent the terminal echoing the character? I thought it was only useful for grabbing control keys as well as regular chars.
Martin Beckett
The C compiler doesn't have getch(), that's part of the curses library. And getch() doesn't necessarily echo, but you have to use the other curses library functions to turn off echoing. Otherwise, it will echo by default.
Chris Lutz
getch() is also part of conio.h in windows and it does not echo by default.
Carson Myers
+2  A: 

Since your task is fairly basic, if you're lucky your system will have the getpass() function:

char * getpass(const char *prompt);

If you don't want a prompt, just do:

char s[129]; /* getpass() only reads up to 128 characters
              * at least on my system. It might work better
              * if you use a char* instead of a char[], but
              * it might work fine either way.
              */
s = getpass("");
printf("Your password was %s!\n", s);

getpass(), like all C functions related to echo and buffering, is non-standard, but present on Mac OS X, probably Linux, and is listed in the GNU C library, so it's probably present on any system using glibc.

The ANSI and ISO standards, as stated previously, do not specify a standard way to read input without echoing, or to read unbuffered input (i.e. on character at a time).

Chris Lutz