scanf问题

#include<stdio.h>
int main()
{
int i,a[6]={3,2,4,9,23,10},b[6]={2,8,5,8,21,30},A[6]={1,10,2,3,32,40,},B[6]={7,7,9,4,44,32},C[6]={5,6,3,5,67,68},D[6]={0,1,1,17,87,90};
char s[7]="CABDBA",t[7];
for(i=0;i<=5;i++)
{
printf("第%d题:%d+%d=(  )\n",i+1,a[i],b[i]);
printf("A.%d\tB.%d\nC.%d\tD.%d\n",A[i],B[i],C[i],D[i]);
printf("Please input you answer : ");

scanf(" %c",&t[i]);

if(t[i]==s[i])
{
    printf("you are right\n");
}
else
{
    printf("you are wrong\n");
}
//getchar();这种解决办法也可以
printf("\n");
}
return 0;
}

初涉c语言,刚开始学习遇到一个奇怪的问题程序代码如下:

#include<stdio.h>
int main(void)
{
char name[5];

scanf("%s", name);
printf("your name:%s\n", name);
}

我定义的char数组长度是5,但是我输入hellohellohello 程序都没有报错为什么呢 我只定义5个长度的字符数组啊,再输入hellohellohellohellohello 就报错 错误(core dumped)
这是什么情况啊?

原因是:
如果定了char [4]; 系统只会分配5个字节空间的,一个结束符’\0’;

scanf输出超出长度,会在标准输入缓冲区中,当你刷新了缓冲区的话,就会出问题的,结果是不可欲知的!

为了预防这种情况的发生,

#include<stdio.h>
int main(void)
{
char name[5];

scanf("%4s", name);
printf("your name:%s\n", name);
}

一样可以输入很多字符,但是只往name内放入4个字符。

#include<stdio.h>
#include<stdlib.h>
int main()
{
int a,b;
char c1,c2;
scanf("%d,%d",&a,&b); //输入的格式应该为1,2
printf("%d,%d\n",a,b);//不要管这个输出,无所谓
getchar();//如果没有这个,那么a为换行符了...
scanf("%c%c",&c1,&c2);//你在两个%d之间加了个逗号(,) 所以你输入的时候两个量也必须用逗号分割!!!
printf("c1='%c',c2='%c'\n",c1,c2);
system("pause");
return 0;
}
#include<stdio.h>
int main()
{
    char a,b,c;
    scanf("%c %c %c",&a,&b,&c);
    printf("%c%c%c\n",a,b,c);
    return 0;
}

看到了输入格式的正确性了吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值