getchar和putchar

1.getchar的用法:(头文件stdio.h)

当程序调用getchar时,程序等待用户输入。用户输入的字符将被存放在键盘缓存区中,直到用户按回车键为止(回车字符也放在缓存区中)。当用户键入回车,getchar才开始从stdin流中每次读入一个字符。getchar函数的返回值是用户输入的第一个字符的ASCII码,如出错返回-1.且将用户输入的字符回显到屏幕。

代码示例:(将字符串转化为实数)

#include <stdio.h>
#include <conio.h>
//将字符串转化为实数 
int main(){
	char x='A',y='B',z='a',t='b',dot='a';
	int i=0,j=0,k,m;
	double fk=0,fn=0;
	
	printf("please input 5 digit(for example 12.45):");
	x=getch();
	y=getch();
	dot=getch();
	z=getch();
	t=getch();
	i=x-'0';
	j=y-48;
	k=z-48;
	m=t-'0';
	fk=i*10+j+(k/10.0)+(m/100.0);
	fn=(i*10+j)+(k*1.0+m/10.0)/10.0;
	//秦九韶算法 ,节约乘法次数。 
	printf("you input is:%c %c %c %c\n,translate to decimal k:%lf,n=%lf\n\n",x,y,z,t,fk,fn);
}

将实数转化为字符:

#include <stdio.h>
#include <math.h>
int main(){
	char x='A',y='B',z='a',t='b',dot='a';
	int i=0,j=0,k=0,m=0,n=0;
	double fa=0,fb=0,fc=0;
	printf("please input decimal(12.35):");
	scanf("%lf",&fa);
	i=(int)floor(fa);
	j=i%10;
	y=j+48;
	k=i/10;
	x=k+'0';
	fb=fa-floor(fa);
	fb=fb*100;
	n=(int)floor(fb+0.1);//有时候有问题
	printf("after expand 100 and convert to integer:%d\n",n);
	k=n/10;
	z=k+'0';
	j=n%10;
	t=j+'0';
	printf("you input is:%lf\ntranslate to char:%c%c.%c%c\n\n",fa,x,y,z,t);
}

2.putchar的用法:(头文件stdio.h)

putchar函数是字符输出函数, 其功能是在显示器上输出单个字符。其一般形式为: putchar(字符变量) 例如:
putchar('A'); 输出大写字母A
putchar(x); 输出字符变量x的值

putchar('\n'); 换行 对控制字符则执行控制功能,不在屏幕上显示。

putchar()这个函数不会检查要输出的字符的真正范围。 在使用的时候需要注意,输出变量的范围是不是一个字符的范围内,只有在一个字符的范围内才能正确输出,不然肯定会出错。


代码示例:

#include<stdio.h>
#include<conio.h> 
int main(){
	char c;
	int aeiou=0,other=0,iother=0;
	while(1){
		c=getch(); 
		putchar(c);
		if(c==13){
			break;
		}
		else{
		if(((c>='A')&&(c<='Z'))||((c>='a')&&(c<='z'))){
			if((c=='a')||(c=='A')||(c=='E')||(c=='e')||(c=='I')||(c=='i')||(c=='o')||(c=='O')||(c=='U')||(c=='u'))
		    {
		    	aeiou++;
			}
			else{
				other++;
			}
		}
		else{
			iother++;
		}
	  } 
    }
	  printf("元音字母:%d,其他字母:%d,非字母:%d\n",aeiou,other,iother);
}

3.getch()用法:同getchar,只是不回显。而且头文件是conio.h
  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值