我正在编写一个简单的 Objective - C 控制台应用程序。 我只想接受数字。 即使我输入一个不是数字的字符,它也不应该被回显。 我应该有一个字符数组,其中包含我可以使用 atoi() 的所有数字。
scanf 有格式化程序,但它们无法按我想要的方式工作。 我知道这应该是可能的。当你在终端输入密码时它的工作方式, 他们只是被接受但没有回应。
我只是想要它的一个变体。
是否有一些 C 函数只接受一个字符并返回它但不在屏幕上回显它?
最佳答案
查看这些链接以获取更多信息 What is Equivalent to getch() & getche() in Linux?
你可以使用 getch() 但如果没有 getch() 那么你可以尝试下面的代码。
#include <termios.h>
#include <stdio.h>
static struct termios old, new;
/* Initialize new terminal i/o settings */
void initTermios(int echo)
{
tcgetattr(0, &old); /* grab old terminal i/o settings */
new = old; /* make new settings same as old settings */
new.c_lflag &= ~ICANON; /* disable buffered i/o */
new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}
/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
/* Read 1 character without echo */
char getch(void)
{
return getch_(0);
}
/* Read 1 character with echo */
char getche(void)
{
return getch_(1);
}
/* Let's test it out */
int main(void) {
char c;
printf("(getche example) please type a letter: ");
c = getche();
printf("\nYou typed: %c\n", c);
printf("(getch example) please type a letter...");
c = getch();
printf("\nYou typed: %c\n", c);
return 0;
}
Getch 函数获取字符但不回显到屏幕。
谢谢
关于objective-c - 如何从 C 中的控制台接受 "only characters"或 "only digits"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8473081/