Ç - 这样的命令写在终端,但不执行与终端交互
问题描述:
system("clear");
printf("Enter a value :");`
int c = getchar();
这会导致终端要求一个角色这样
Enter a value:
我要的是该程序建议一个值,好像用户键入的值,但没有按下输入,如下所示:
Enter a value: 5
然后用户可以按回车键和getchar()
将收到5
或退格5
并输入他们想要的任何值
这可能吗?
答
这是一种方式,你可以做到这一点
#include <stdio.h>
#include <stdlib.h>
int main(){
char input[100] = "5";
int pos = 1;
int c_read = 0;
printf("Enter a value: 5");
while (1){
c_read = getch();
if (c_read == 13 || c_read == -1){
printf("\n");
break;
}
if (c_read == 8){
if(pos == 0)
continue;
pos--;
input[pos] = '\0';
printf("\b \b");
}else{
if (pos == 99)
continue;
printf("%c", c_read);
input[pos] = c_read;
pos++;
input[pos] = '\0';
}
}
printf("You entered %s\n", input);
}
Ofcourse这里使用了神可怕getch
。您可以在Linux上的ncurses
库中找到它,并在Windows上随附MinGW。
您可以用getch
替代getch
以从键盘读取字符。
此外,我将它留给你在使用前将字符串转换为数字。
PS:如果您正在为您缓冲并且没有反映更改,您可能还必须在每次打印后输入fflush(stdout)
。
+0
@KamiKaze在Windows上为MinGW工作。 –
'srand(time(NULL)); int val = rand()%50; printf(“输入一个值:%d”,val);'会工作。 (包括'stdlib.h'和'time.h'头文件)如下所述,您将不得不'scanf'值并替换最初显示的数字。 –
通过在控制台中用'\ b''填充'stdin',通常不会擦除写入'stdout'的字符。但是,你可以做的是逐个字符地读取输入,然后在输入是''\ b''时删除一些字符。我可以写一个答案演示相同。 –
@ DavidC.Rankin这不是他想要的(据我所知)。 –