我想寫一行代碼,當你輸入4個數字時,計算機在輸入一組數字后自動按回車,我該怎么做?
uj5u.com熱心網友回復:
使用GNU readline或多或少可移植的解決方案:
#include <readline/readline.h>
#include <stdio.h>
#include <stdlib.h>
static int limit_rl(FILE *f)
{
if (rl_end >= 4)
{
return '\n';
}
return rl_getc(f);
}
int main(void)
{
char *str;
rl_getc_function = limit_rl;
str = readline("> ");
printf("%s\n", str);
free(str);
return 0;
}
uj5u.com熱心網友回復:
這取決于您的作業系統:
例如,在 linux 系統上,system呼叫:
#include <stdio.h>
#include <stdlib.h>
int main(void){
int c;
int passwd[4]={0};
system ("/bin/stty raw"); //use system call to make terminal send all keystrokes directly to stdin
for(unsigned short nb_char = 0; nb_char < 4; nb_char )
{
do
{
c=getchar();
}while((c < 48) || (c > 57));
passwd[nb_char] = c;
}
printf("\npassword is:");
for(unsigned short nb_char = 0; nb_char < 4; nb_char )
{
putchar(passwd[nb_char]);
}
system ("/bin/stty cooked");//use system call to set terminal behaviour to more normal behaviour
return 0;
}
輸出是:
1234
password is:1234
對于窗戶,請參閱getch():
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main(void){
int c;
int passwd[4]={0};
for(unsigned short nb_char = 0; nb_char < 4; nb_char )
{
do
{
c=getch();
}while((c < 48) || (c > 57));
passwd[nb_char] = c;
}
printf("\npassword is:");
for(unsigned short nb_char = 0; nb_char < 4; nb_char )
{
putchar(passwd[nb_char]);
}
return 0;
}
請參閱此答案以獲取完整答案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/396802.html
