有没有办法只删除用户输入而不删除整个程序?这是程序
#include <stdio.h>
int main() {
int a;
printf("text");
scanf("%d", &a);
}
如果我做clrscr()
,它会删除所有内容,而这不是我想要的.
有没有办法只删除用户输入而不删除整个程序?这是程序
#include <stdio.h>
int main() {
int a;
printf("text");
scanf("%d", &a);
}
如果我做clrscr()
,它会删除所有内容,而这不是我想要的.
有两种可能的方法可以解决您的问题:
您可以try 阻止用户输入 echo 到终端.这需要使用特定于系统的调用(如tcgetattr()
和tcsetattr()
)来更改终端的配置,这非常棘手且容易出错.
您可以在验证用户输入后,使用ANSI escape sequences向上移动光标并终止行的结尾,try 删除用户输入.这要简单得多,但不是万无一失的,当然它也不会阻止用户在键入敏感数据时用肉眼观看屏幕.
下面是一个例子:
#include <stdio.h>
char *get_string(const char *prompt, char *dest, size_t size) {
printf("\r%s: \033[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("\r\033[A%s: \033[K\n", prompt);
return dest;
}