[英]I am having trouble with receiving keypresses in C
我正在嘗試一些練習題,這是其中之一。 我想我應該使用getch來接收按鍵,而無需用戶按下Enter鍵,但是我不知道如何執行此操作。 請幫忙。
問題:編寫一個程序,計算直到用戶按下“!”為止所按下的鍵數 鍵。 當。。。的時候 '!' 按下該程序應在屏幕上顯示按鍵計數,然后終止。
我的代碼:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, counter;
i = 0;
counter = 0;
char input;
while (i==0)
{
scanf("%c", &input);
if (input == "!");
{
i = 1;
}
counter ++;
}
printf("Keystrokes = %d", counter);
return 0;
}
打開編譯器警告,並注意它們。
if (input == "!");
// ^ ^ ^
if (input == '!')
除了上面的錯誤和需要回車之外,您的程序應該可以正常工作。
以下代碼無需按ENTER鍵即可工作。 但不會在終端中顯示任何輸入。 但是按下后會顯示按下了多少鍵!
。
#include <stdio.h>
#include <conio.h>
int main()
{
int i, counter;
i = 0;
counter = 0;
while(1)
{
if(getch()=='!')
break;
counter++;
}
printf("Keystrokes = %d", counter);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(){
int counter;
counter = 0;
char input = '0';
while (input != '!'){
scanf("%c", &input);
if(input != '\n')
counter ++;
}
printf("Keystrokes = %d", counter);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.