getch()是非標準函數,存在於conio.h頭文件中,該文件通常由Turbo C等MS-DOS編譯器使用。它不是C標準庫或ISO C的一部分,也不由POSIX定義。
像這些函數一樣,getch()也從鍵盤讀取單個字符。但是它不使用任何緩衝區,因此無需等待回車鍵即可立即返回輸入的字符。
用法:
int getch(void);
參數:此方法不接受任何參數。
返回值:此方法返回按鍵的ASCII值。
例:
// Example for getch() in C
#include <stdio.h>
// Library where getch() is stored
#include <conio.h>
int main()
{
printf("%c", getch());
return 0;
}
Input: g (Without enter key) Output: Program terminates immediately. But when you use DOS shell in Turbo C, it shows a single g, i.e., 'g'
關於getch()方法的要點:
- getch()方法會暫停輸出控製台,直到按下一個鍵為止。
- 它不使用任何緩衝區來存儲輸入字符。
- 輸入的字符將立即返回,而無需等待回車鍵。
- 輸入的字符不會顯示在控製台上。
- getch()方法可用於接受隱藏的輸入,例如密碼,ATM針號等。
示例:使用getch()接受隱藏的密碼
注意:以下代碼不會在在線編譯器上運行,但會在Turbo IDE等MS-DOS編譯器上運行。
// C code to illustrate working of
// getch() to accept hidden inputs
#include <conio.h>
#include <dos.h> // delay()
#include <stdio.h>
#include <string.h>
void main()
{
// Taking the password of 8 characters
char pwd[9];
int i;
// To clear the screen
clrscr();
printf("Enter Password:");
for (i = 0; i < 8; i++) {
// Get the hidden input
// using getch() method
pwd[i] = getch();
// Print * to show that
// a character is entered
printf("*");
}
pwd[i] = '\0';
printf("\n");
// Now the hidden input is stored in pwd[]
// So any operation can be done on it
// Here we are just printing
printf("Entered password:");
for (i = 0; pwd[i] != '\0'; i++)
printf("%c", pwd[i]);
// Now the console will wait
// for a key to be pressed
getch();
}
輸出:
Abcd1234
輸出:
Enter Password:******** Entered password:Abcd1234
相關用法
- C++ btowc()用法及代碼示例
- C++ wcsspn()用法及代碼示例
- C語言 fopen()用法及代碼示例
- C語言 getdate()、setdate()用法及代碼示例
- C++ mbrtoc32()用法及代碼示例
- C++ mbrtoc16()用法及代碼示例
- C++ wmemset()用法及代碼示例
注:本文由純淨天空篩選整理自AnshulVaidya大神的英文原創作品 getch() function in C with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。