求助,为什么如下代码执行时“sex =name =”会被同时输出?
c吧
全部回复
仅看楼主
level 1
函数的目的是动态构建存放学生信息的结构体数组
#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct Student
{
char sex;
float score;
char name[100];
};
void sort(struct Student * parr,int len);
void output_score(struct Student * parr,int len);
void input_score(struct Student * parr,int len);
int main()
{
int len;
struct Student * parr;
printf("please input the number of students:");
scanf("%d",&len);
parr = (struct Student *) malloc(len * sizeof(struct Student));
input_score(parr,len);
sort(parr,len);
output_score(parr,len);
free(parr);
return 0;
}
void sort(struct Student * parr,int len)
{
int i,j;
struct Student t;
for (i = 0; i < len; ++i)
{
for (j = 0; j < len-1-i; ++j)
{
if(parr[j].score < parr[j+1].score)
{
t = parr[j]; parr[j] = parr[j+1]; parr[j+1] = t;
}
}
}
}
void output_score(struct Student * parr,int len)
{
int i;
for (i = 0; i < len; ++i)
{
printf("the number of %d's information is:\n",i+1);
printf("sex:%c\n",parr[i].sex);
printf("score:%.2f\n",parr[i].score);
printf("name:%s\n",parr[i].name);
}
}
void input_score(struct Student * parr,int len)
{
int i;
for (i = 0; i < len; ++i)
{
printf("please input the number of %d's information\n",i+1);
printf("sex =");
scanf("%c",&parr[i].sex);
printf("name =");
scanf("%s",parr[i].name);
printf("score =");
scanf("%f",&parr[i].score);
}
}
输出结果:
2023年01月06日 01点01分 1
level 11
真奇妙,把输入性别的语句改成cin就没问题了[滑稽]
2023年01月07日 04点01分 2
还没学cpp[狂汗],用c的语法不能解决吗?
2023年01月07日 23点01分
level 1
这是你自己写的不是Ctrl c Ctrl v,我直接从五楼跳下去[哈哈][哈哈]
2023年01月08日 14点01分 3
。。。我照老师的代码敲的,就算ctrl v了吧[吐舌]
2023年01月09日 06点01分
level 1
那你copy都没copy明白
2023年01月09日 17点01分 4
把sex数据类型改为数组可正常运行,我只是想知道为什么字符不行[黑线]
2023年01月10日 04点01分
level 9
我觉得是你在使用scanf时写入sex用了%c
这导致你把输入流中的回车给读取到了sex,跳过了sex的输入,至于回车怎么来的应该是你输入长度1时的回车,解决也简单,你直接在执行写入sex前进行一次读取一个字符操作就行了。不过都用c++了,直接用cin不好吗?[黑线]
2023年02月12日 14点02分 5
解决了,谢谢大佬,还有这个没用cpp[笑眼]
2023年02月21日 09点02分
1