VC编程,C语言,scanf,printf问题

u013984264 2014-05-14 11:14:01
前面有定义结构体
struct student
{
int num;
char name[10];
int score[3];
};

以下是用3种情况输入一个学生的信息:
第一种:for(i=0;i<1;i++) //name放最后
{
printf("Input the number,name,and three scores of the %dth student:\n",i+1);
scanf("%d,%d,%d,%d,%s",&a[i].num,&a[i].score[0],&a[i].score[1],&a[i].score[2],a[i].name);
}

第二种:for(i=0;i<1;i++) //name不放最后
{
printf("Input the number,name,and three scores of the %dth student:\n",i+1);
scanf("%d,%s",&a[i].num,a[i].name);
scanf("%d",&a[i].score[0]);
scanf("%d",&a[i].score[1]);
scanf("%d",&a[i].score[2]);
}

第三种:for(i=0;i<1;i++) //name不放最后
{
printf("Input the number,name,and three scores of the %dth student:\n",i+1);
scanf("%d,%s,%d,%d,%d",&a[i].num,a[i].name,&a[i].score[0],&a[i].score[0],&a[i].score[0]);
}

打印的话都是用这个语句:for(i=0;i<1;i++)
{
printf("\n输出上面的信息:");
printf("%d,%s,%d,%d,%d",a[i].num,a[i].name,a[i].score[0],a[i].score[1],a[i].score[2]);
}
三种方法分别对应的输出显示情况如下:




但是我最想用的第3种方法,但是后面乱码,请问怎么回事?我猜是scanf的回车键结束引起的,但是不知道它内部怎么读数据的?有大神不?
...全文
176 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2014-05-14
  • 打赏
  • 举报
回复
worldy 2014-05-14
  • 打赏
  • 举报
回复
谁先谁后都没关系,重要的是你的格式、变量、实际输入顺序需要能对应起来
赵4老师 2014-05-14
  • 打赏
  • 举报
回复
printf里面的%和变量的一一对应关系 scanf里面的%和变量以及变量前加不加&的一一对应关系 是C代码中非常容易出错的地方,而且通常编译还不出错。 所以在编译源代码之前值得专门仔细检查一遍甚至多遍。 在每个最后不带\n的printf后面加fflush(stdout); 在每个不想受接收缓冲区旧内容影响的scanf前面加rewind(stdin); 另外请检查scanf的返回值。
我还在迷路 2014-05-14
  • 打赏
  • 举报
回复
引用
第三种:for(i=0;i<1;i++) //name不放最后 { printf("Input the number,name,and three scores of the %dth student:\n",i+1); scanf("%d,%s,%d,%d,%d",&a[i].num,a[i].name,&a[i].score[0],&a[i].score[0],&a[i].score[0]); }
输入的时候,第二部分接收的内容为bao,78,79,90,后面的3个输入整形等于没有初始化 建议你改成

printf("Input the number,name,and three scores of the %dth student:\n",i+1);
                      scanf("%d,%d,%d,%d,%s",&a[i].num,&a[i].score[0],&a[i].score[0],&a[i].score[0],a[i].name);
把名字放在最后面
u013984264 2014-05-14
  • 打赏
  • 举报
回复
别沉啊!!!!!!!!!1
我还在迷路 2014-05-14
  • 打赏
  • 举报
回复
%d的输入可以以“,”或者空格 或者回车来区分,但%s 不能以“,”区分,你的输入中,第一个参数传递给%d,遇到“,”正确传递,但是第二个传值是%s,“,”会被当做该参数的内容一并传递,一直到遇到回车符 %s才赋值结束 你分开打印就会发现%s内容保存的内容了

69,375

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧