#include#include #include <string.h> void main() { int a; char b; float c; printf("please input an integer:"); scanf("%d", &a); printf("integer:%d\n", a); printf("please input an character:"); getchar();/*将缓冲区的回车读走,如没有getchar(),scanf("%c",&b)会把回车读走,从而不能顺利输入字符型,scanf在读取字符型时需要区别对待,
因为它会读走回车,要加入getchar(),读取其他整型和float等类型时不用*/ scanf("%c", &b); printf("character:%c\n", b); printf("please input a float number:"); scanf("%f", &c); printf("float:%f\n", c); }
有getchar():的运行结果
没加入getchar():运行到输入字符串阶段发现是直接跳过的,因为scanf("%c",b)直接读取了缓冲区中的回车换行符(因为上一步我输入了12和回车换行符,12被 scanf("%d",&a);读走,所以只剩下回车换行符)
/* Note:Your choice is C IDE */ #include "stdio.h" void main() { int a; char b; float c; printf("please input an integer:"); scanf("%d",&a); printf("integer:%d\n",a); printf("please input an character:"); scanf("%c",&b); printf("character:%c\n",b) ; printf("please input a float number:"); scanf("%f",&c); printf("float:%f\n",c) ; }
不用getchar()的解决方法,在 scanf(" %c",&b);“即%号前加个空格,他的意义是自动忽略空白字符,包括回车换行,tab,空格键这些”
/* Note:Your choice is C IDE */ #include "stdio.h" void main() { int a; char b; float c; printf("please input an integer:"); scanf("%d",&a); printf("integer:%d\n",a); printf("please input an character:"); scanf(" %c",&b); printf("character:%c\n",b) ; printf("please input a float number:"); scanf("%f",&c); printf("float:%f\n",c) ; }
-----------------------------------------------------------------------------------------------------------------------------
相比较之下,我比较喜欢C++,不用考虑这些东西,下面是C++代码:
// Note:Your choice is C++ IDE #includeusing namespace std; int main() { int a; char b; float c; cout<<"please input an integer:"; cin>>a; cout<<"integer:"<endl; cout<<"please input an character:"; cin>>b; cout<<"character:"<endl ; cout<<"please input a float number:"; cin>>c; cout<<"float:%f\n"< endl ; /* return 0;*/ }
scanf(" %c",&b);