鱼C论坛

 找回密码
 立即注册
查看: 3722|回复: 7

关于结构体读取输出 出错

[复制链接]
发表于 2021-5-18 23:23:40 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
为什么这段不能正常读取和输出结构体当中的内容呢
#include<stdio.h> 
#include<string.h>
struct Student
{
        char num;
        char name[20];
        float score;
}student[3];

int main()
{
char max, i;

for(i = 0; i < 3; i++)
{
        scanf("%c%s%f",&student[i].num, student[i].name, &student[i].score);
}

for(i = 0; i < 3; i++)
{
        printf("%c %s %.2f\n",student[i].num, student[i].name,student[i].score);
}

printf("The higer score is:\n");

return 0;
}        
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-5-18 23:25:33 | 显示全部楼层
scanf("%c%s%f",&student[i].num, student[i].name, &student[i].score);
"%c%s%f" // 分割符呢?
student[i].name // &呢?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-5-19 09:09:36 From FishC Mobile | 显示全部楼层
ba21 发表于 2021-5-18 23:25
scanf("%c%s%f",&student.num, student.name, &student.score);
"%c%s%f" // 分割符呢?
student.name / ...

数组不是不用取址吗
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-5-19 09:24:05 | 显示全部楼层
#include<stdio.h> 
#include<string.h>
struct Student
{
    char num;
    char name[20];
    float score;
}student[3];

int main()
{
    //char max, i;
    int max, i;

    for(i = 0; i < 3; i++)
    {
        scanf("%c%s%f",&student[i].num, student[i].name, &student[i].score);
        getchar();
    }

    for(i = 0; i < 3; i++)
    {
        printf("%c %s %.2f\n",student[i].num, student[i].name,student[i].score);
    }

    printf("The higer score is:\n");

    return 0;
}        
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-5-19 09:49:13 From FishC Mobile | 显示全部楼层
人造人 发表于 2021-5-19 09:24

请问这里为什么要加一个getchar呢
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-5-19 10:17:48 | 显示全部楼层
Mr丶张 发表于 2021-5-19 09:49
请问这里为什么要加一个getchar呢

去掉在输入流中最后那个多余的 '\n'
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-5-25 09:08:57 From FishC Mobile | 显示全部楼层
人造人 发表于 2021-5-19 09:24

什么情况下要用getchar()??
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-5-25 09:48:31 | 显示全部楼层
最强废铁h 发表于 2021-5-25 09:08
什么情况下要用getchar()??

当 scanf 最后一个接收的不是 %c 的时候
#include <stdio.h>

int main(void) {
    int a, b, c;
    char ch;
    scanf("%d%d%d", &a, &b, &c);
    getchar();
    scanf("%c", &ch);
    printf("%d, %d, %d, '%c'\n", a, b, c, ch);
    return 0;
}

#include <stdio.h>

int main(void) {
    int a, b, c;
    char ch1, ch2;
    scanf("%d%d%d%c", &a, &b, &c, &ch1);
    scanf("%c", &ch2);
    printf("0x%x, 0x%x\n", ch1, ch2);
    printf("%d, %d, %d\n", a, b, c);
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 10:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表