C语言中使用%c输入数据时的一些问题,在用%c格式符读入字符时,空格字符和转义字符都会作为有效字符输入,
#include <stdio.h>
int main()
{
int a;
char b;
float c;
printf("Please input a integer:");
scanf("%d",&a);
printf("integer:%d\n",a);
printf("Please input a character:");
scanf("%c",&b);
printf("character:%c\n",b);
printf("Please input a float number:");
scanf("%f",&c);
printf("float:%f\n",c);
return 0;
}
此时用%c输出的字符就会出现错误,
Please input a integer:10 integer:10 Please input a character:character:
Please input a float number:1.25 float:1.250000
Process returned 0 (0x0) ? execution time : 7.018 s Press any key to continue. 而我们可以通过加入空格和getchar()函数来解决。
#include <stdio.h>
int main()
{
int a;
char b;
float c;
printf("Please input a integer:");
scanf("%d",&a);
printf("integer:%d\n",a);
printf("Please input a character:");
scanf(" %c",&b);
printf("character:%c\n",b);
printf("Please input a float number:");
scanf("%f",&c);
printf("float:%f\n",c);
return 0;
}
Please input a integer:10 integer:10 Please input a character:a character:a Please input a float number:1.25 float:1.250000
Process returned 0 (0x0) ? execution time : 6.695 s Press any key to continue. ?
#include <stdio.h>
int main()
{
int a;
char b;
float c;
printf("Please input a integer:");
scanf("%d",&a);
printf("integer:%d\n",a);
printf("Please input a character:");
getchar();
scanf("%c",&b);
printf("character:%c\n",b);
printf("Please input a float number:");
scanf("%f",&c);
printf("float:%f\n",c);
return 0;
}
Please input a integer:10 integer:10 Please input a character:a character:a Please input a float number:1.25 float:1.250000
Process returned 0 (0x0) ? execution time : 5.889 s Press any key to continue. ?
这样,问题就解决了。
|