I am trying to create a minigame to play with my friends, where someone puts a number, and then we have 10 tries to guess it. Unfortunately, we a number is scanned, it stays in the terminal, so everyone can read and cheat.
I also tried to do something kinda dumb, which was use printf("\n\n\n\n\n\n\n\n\n\n\n\n\n...")
with 29, but that way the code goes down and looks bad.
Can anyone help me?
Asked
Active
Viewed 69 times
-2
-
Turn off echo in the terminal so the characters are never printed. – William Pursell May 26 '21 at 16:17
-
Or, instead of `\n`, use `\r` and write spaces. – William Pursell May 26 '21 at 16:18
-
Or use terminal control sequences to clear the line. – William Pursell May 26 '21 at 16:18
-
1TIAGO CAMEIRINHA, No general C answer. Solution are terminal/OS specific. What OS and compiler are you using? – chux - Reinstate Monica May 26 '21 at 16:32
4 Answers
1
You didn't specify the platform (OS). In General there are several methods:
- Supressing echo via stty(): See https://stackoverflow.com/a/67709009/6607497
- Using getpass() (obsolete)
- Use terminal escape sequences (like ANSI) to Query the input at a specific line, then erase that line. See https://en.wikipedia.org/wiki/ANSI_escape_code for details.
- Learn to use curses. See http://heather.cs.ucdavis.edu/~matloff/UnixAndC/CLanguage/Curses.pdf for details
- How to disable echo in windows console?
- ANSI C No-echo keyboard input
- https://www.reddit.com/r/C_Programming/comments/64524q/turning_off_echo_in_terminal_using_c/
- https://social.msdn.microsoft.com/Forums/en-US/14220ac4-a557-4cea-b29d-f46222a36ef5/how-to-not-echo-the-input-of-consoleread
- http://www.cplusplus.com/forum/general/3570/
- https://falsinsoft.blogspot.com/2014/05/disable-terminal-echo-in-linux.html
- ...
Maybe you should have searched elsewhere first!

U. Windl
- 3,480
- 26
- 54
0
Probably the simplest thing (but certainly not the best)you can do is shell out to stty
to manipulate the terminal database. Eg:
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
char b[32];
printf("prompt: ");
system("stty -echo"); /* Turn off echo */
if( scanf("%31s", b) == 1 ){
printf("\nyou entered %s\n", b);
}
system("stty echo"); /* Turn echo back on */
return 0;
}
Note that this does not handle signals well, and your terminal may end up with a modified state.

William Pursell
- 204,365
- 48
- 270
- 300
0
If you use windows, you can specifies the maximum number of commands in the history buffer.:
system("doskey /listsize = 0");
In addition, You can simulate the keyboard shortcut ALT+F7 to clear the history.
If you use Unix, you can clean the history:
system("history -c");

Arcaniaco
- 400
- 2
- 10
-
Oh, I would be very angry if some program deletes my shell history! – the busybee May 27 '21 at 06:25
0
if you #include <stdlib.h>, system("cls"); should clear the terminal after the number is entered. I tried the game, its fun!