例:当键盘输入字母‘h’时,打印输出
字符串“Hello!”;当输入字母‘g’时,打印输出字符串“Good!”
如果要实时输出的话可以用getch()
输入的同时程序就自动判断显示,不用按回车。
也就是你键盘按h,屏幕直接显示Hello!,按g屏幕直接显示Good!,不会出现h和g。
#include <stdio.h>
#include <conio.h> //注意添加这个
头文件void main(){
char c;
while(c=getch())
{
if(c=='h')
printf("Hello!");
if(c=='g')
printf("Good!");
}
}
不过这样只有输入h和g时才有反应
如果不是要实时的判断,可以用getchar()
这个要你输入并按回车后才开始判断显示。这样屏幕上会留下你原来输入的h或g
#include <stdio.h>
void main(){
char c;
while(c=getchar())
{
if(c=='h')
printf("Hello!");
if(c=='g')
printf("Good!");
}
}