[英]Why does getchar() only return (char)13 after another key has been pressed? (windows)
[英]Why is the input displayed after the enter key has been pressed?
#include <stdio.h>
/* copy input to output */
main()
{
int c;
c = getchar();
while(c != EOF)
{
putchar(c);
c = getchar();
}
return 0;
}
在給定的代碼中,程序顯示輸入字符。 它逐個讀取每個字符(進入變量“ c”),並同時輸出相同的讀取字符。 當輸入EOF字符時,程序終止。
當我在IDE中運行代碼(代碼:: Blocks 16.01)並輸入字符串時,例如:Hi! 我叫C。\\ n
輸出顯示在“ \\ n”之后,而不同時顯示。 是不是應該作為輸出- “H H I I M M Y Y N N一A M M E E I 我 ššC C!。”?
粗體字母表示輸出。
包括:
#include <unistd.h>
#include <termios.h>
在主插入代碼之前:
struct termios term, term_orig;
if(tcgetattr(STDIN_FILENO, &term_orig)) {
printf("tcgetattr failed\n");
return -1;
}
term = term_orig;
term.c_lflag &= ~ICANON;
if (tcsetattr(STDIN_FILENO, TCSANOW, &term)) {
printf("tcsetattr failed\n");
return -1;
}
在代碼插入后:
if (tcsetattr(STDIN_FILENO, TCSANOW, &term_orig)) {
printf("tcsetattr failed\n");
return -1;
}
因為默認情況下, 來自terminal的輸入是line-buffered的 。 因此,在按Enter鍵后,程序會得到整行。
要在Unix和Linux系統中禁用緩沖,請嘗試以下操作:
#include <unistd.h>
#include <termios.h>
int disableLineBuffer(void){
struct termios term, oldterm;
if (tcgetattr(STDIN_FILENO, &term)) return -1;
oldterm = term;
term.c_lflag &= ~(ECHO | ICANON);
if (tcsetattr(STDIN_FILENO, TCSANOW, &term)) return -1;
return 0;
}
在Windows中,請改為執行以下操作:
#include <windows.h>
BOOL WINAPI DisableLineBuffer(void){
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
if (!GetConsoleMode(hInput, &mode)) return FALSE;
mode &= ~ENABLE_LINE_INPUT;
if (!SetConsoleMode(hInput, mode)) return FALSE;
return TRUE;
}
請確保在退出程序之前將更改還原到控制台,否則您可能無法在終端上執行任何其他操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.