繁体   English   中英

我在使用C按键时遇到麻烦

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM