我想通过scanf将字符和整数输入到结构中

I want to input character and integers by scanf into a structure

本文关键字:输入 整数 结构 字符 scanf      更新时间:2023-10-16

好的,所以我想使用 scanf 在结构中输入一个字母字符和三个数字,我想使用打印它的函数打印所有四个字符。但是每次我运行它时,我都会收到错误,说我无法运行它,或者有时它会正确打印除字符部分之外的所有内容,它只会变为空白。这可能有什么问题??

#include <stdio.h>
struct Score
{
    char a;
    float x, y, z;
};


void main(void)
{
void avg(char *a, float x, float y, float z);

    char a1 = 'b';
    float x1 = 0, y1 = 0, z1 = 0;
    printf("enter an alphabern");
    fflush(stdin);
    scanf_s("%c", &a1);
    printf("enter three numbers (ex:1,2,3)n");
    fflush(stdin);
    scanf_s("%f,%f,%f", &x1, &y1, &z1);

    struct Score s1 = { a1, x1, y1, z1 };

    avg(s1.a, s1.x, s1.y, s1.z);

}
void avg(char *a, float x, float y, float z)
{
    printf("%c (%f,%f,%f) n", a, x, y, z);
}

avg()的签名是错误的。第一个参数不应该是char*而是char

因为我讨厌特定于 MSVC 的代码,所以您的代码应该是这样的。请注意,您应该检查读取是否成功。

#include <stdio.h>
struct Score
{
    char a;
    float x, y, z;
};
int main(void)
{
    /* declareing function inside function is unusual, but not bad */
    void avg(char a, float x, float y, float z);
    char a1 = 'b';
    float x1 = 0, y1 = 0, z1 = 0;
    printf("enter an alphabern");
    if (scanf("%c", &a1) != 1) {
        puts("read error");
        return 1;
    }
    printf("enter three numbers (ex:1,2,3)n");
    if (scanf("%f,%f,%f", &x1, &y1, &z1) != 3) {
        puts("read error");
        return 1;
    }
    struct Score s1 = { a1, x1, y1, z1 };
    avg(s1.a, s1.x, s1.y, s1.z);
}
void avg(char a, float x, float y, float z)
{
    printf("%c (%f,%f,%f) n", a, x, y, z);
}