每次在C中输入后如何自动按“ ENTER”键?

时间:2018-08-12 18:30:28

标签: c

我正在制作一个软件,每次用户输入数字后,都会自动按下 ENTER 键(我的意思是,将在不按 ENTER的情况下分配该值)。

示例代码:

#include<stdio.h>

int main(){
int i, num[10];

for(i=0; i<10; i++){
    scanf("%d", &num[i]);  

    /*this is where I need help. 
    Every time after typing a single number, the program should store the value
    and move on to next position without requiring the user to press ENTER. How do I
    do that ? */
}

2 个答案:

答案 0 :(得分:2)

您可以使用getch()函数,但只能读取0到9之间的数字。 接下来,您可以使用(int)(ch)-48)转换为int,例如:

char ch;
ch=getch();
printf("%d", (ch - '0'));

/*You can do this too*/
// printf("%d", ((int)(ch)-48));  

数字48是ascii表中的“ 0”。

答案 1 :(得分:1)

如果要避免像给定答案中建议的那样从getch()中脱离conio.h,请使用getchar()中的stdio.h

相关问题