仅删除用户输入,而不是整个屏幕
Delete only user input, not the entire screen
有没有办法只删除用户输入而不删除整个程序?这是程序
#include <stdio.h>
int main() {
int a;
printf("text");
scanf("%d", &a);
}
如果我这样做 clrscr()
它会删除所有内容,这不是我想要的。
有 2 种可能的方法可以解决您的问题:
您可以尝试阻止用户输入回显到终端。这需要使用 tcgetattr()
and tcsetattr()
等系统特定调用来更改终端的配置,这非常棘手且容易出错。
您可以尝试在使用 ANSI escape sequences 验证用户输入后删除用户输入,向上移动光标并删除行尾。这要简单得多,但不是万无一失的,当然,它不会阻止隐私眼睛在用户键入敏感数据时查看屏幕。
这是一个例子:
#include <stdio.h>
char *get_string(const char *prompt, char *dest, size_t size) {
printf("\r%s: 3[K", prompt);
if (!fgets(dest, size, stdin)))
return NULL;
// assuming the cursor is on the next line, move it
// to the beginning of the line, then up one line, show the prompt again
// erase the end of the line and skip to the next line
printf("\r3[A%s: 3[K\n", prompt);
return dest;
}
有没有办法只删除用户输入而不删除整个程序?这是程序
#include <stdio.h>
int main() {
int a;
printf("text");
scanf("%d", &a);
}
如果我这样做 clrscr()
它会删除所有内容,这不是我想要的。
有 2 种可能的方法可以解决您的问题:
您可以尝试阻止用户输入回显到终端。这需要使用
tcgetattr()
andtcsetattr()
等系统特定调用来更改终端的配置,这非常棘手且容易出错。您可以尝试在使用 ANSI escape sequences 验证用户输入后删除用户输入,向上移动光标并删除行尾。这要简单得多,但不是万无一失的,当然,它不会阻止隐私眼睛在用户键入敏感数据时查看屏幕。
这是一个例子:
#include <stdio.h>
char *get_string(const char *prompt, char *dest, size_t size) {
printf("\r%s: 3[K", prompt);
if (!fgets(dest, size, stdin)))
return NULL;
// assuming the cursor is on the next line, move it
// to the beginning of the line, then up one line, show the prompt again
// erase the end of the line and skip to the next line
printf("\r3[A%s: 3[K\n", prompt);
return dest;
}